JDK15 features

1. Overview of JAVA15

On September 15, 2020, java15 was officially released. (A calm version) with a total of 14 JEPs, which is the sixth version released in a time-driven format. Related documents: https://openjdk.java.net/projects/jdk/15/

image.png

image.png

2. Changes at the grammatical level

1. Sealing class (preview)

Enhance the Java programming language with sealed classes and interfaces, a new preview feature for restricting superclasses using sealed classes and interfaces to restrict other classes or interfaces that can inherit or implement them.

Allowing the developer of a class or interface to control which code is responsible for implementation provides more choices than restricting access modifier declarations to superclasses, and supports future developments in pattern matching by enabling exhaustive analysis of patterns.

In Java, the class hierarchy realizes code reuse through integration, and the methods of the parent class can be inherited by many subclasses. However, the purpose of class-level interfaces is not always to reuse code. Sometimes this involves modeling the possibilities that exist in the domain, such as the shape types that a graphics library supports. When using class hierarchies in this way, we may need to limit the set of subclasses to simplify modeling.

Although we can limit subclass inheritance through final, this is to absolutely eliminate class subclasses, while class sealing allows subclasses, but the limit is which one or which ones.

Introducing Seald classes or interfaces, these classes or interfaces only allow the specified classes or interfaces to be extended and implemented.

Using the modifier sealed, we can declare a class as a sealed class. A sealed class uses the reserved keyword permits to list classes that can directly extend it. Subclasses can be final, unsealed or sealed.

Sample code:

public class TestSealedClass {
    
    
}
/*sealed 对Person类进行密封
* permits 指明哪些类可以继承
* 子类必须是final修饰的或者也是密封的
* 如果子类不想被密封,可以使用non-sealed修饰
* */
sealed class Person permits WorkerTeacherCookBossEmployeeStudent {
    
    }
final class Cook              extends Person{
    
    }
final class Boss              extends Person{
    
    }
final class Employee          extends Person{
    
    }
final class Teacher           extends Person{
    
    }
// 密封的子类允许继续有子类
sealed class Student          extends Person permits PrimaryStudentGraduateStudent{
    
    }
final class PrimaryStudent    extends Student{
    
    }
final class GraduateStudent   extends Student{
    
    }
// 通过non-sealed取消子类密封
non-sealed class Worker       extends Person{
    
    }
class CarWorker               extends Worker{
    
    }

Specify the interface of the implementation class

public class Test2 {
    
    
}

/*
* 只有接口可以继承接口
* 一个接口可以同时继承多个接口
* final不能修饰接口,密封接口在被继承时,子接口要么使用 sealed non sealed  修饰
* */
sealed interface  Myinter1 permits Myinter3{
    
    }
sealed interface  Myinter2 permits Myinter3 {
    
    }
sealed interface  Myinter3 extends Myinter1Myinter2{
    
    }
non-sealed class MyImpl implements Myinter3{
    
    }

sealed interface I permits ABC  {
    
    }
final class A implements I{
    
    }
sealed class B implements I{
    
    }
non-sealed class C implements I{
    
    }

final class D extends B{
    
    }

Sealed interfaces cannot be implemented using anonymous inner classes

Sealed columns vs. interface and pattern matching issues

public class TestSealedClass {
    
    
    public static void main(String[] args) {
    
    
        test(new C());
    }
    public static void test(C c){
    
    
        if( c instanceof I){
    
    
            System.out.println( "it is an i");
        }else{
    
    
            System.out.println("it is not i");
        }
    }

}
interface I{
    
    

}
sealed class C implements I permits DE{
    
    }
non-sealed class D extends C{
    
    }
final class E extends C {
    
    }
// 密封类仅仅是控制类的继承和实现关系,不会影响我们的模式匹配

Sealed interfaces and records

Record is implicitly final and can directly implement the sealed interface.


public class TestRecords {
    
    
    public static void main(String[] args) {
    
    
        MyInter1 myInter1=new Person(10"旋涡刘能");

    }
}

sealed interface  MyInter1{
    
    
    public void eat();
}

/*record 默认继承的 java.lang.Record
* record可以直接实现密封接口,不需要用sealed 修饰 non-sealed 修饰
* record本身是隐式的final修饰
*
* */

record Person(Integer pid,String pname)  implements MyInter1 {
    
    
    @Override
    public void eat() {
    
    

    }
}
record Student(Integer pid,String pname) implements MyInter1{
    
    
    @Override
    public void eat() {
    
    

    }
}
record Cook(Integer pid,String pname) implements MyInter1{
    
    
    @Override
    public void eat() {
    
    

    }
}
record Worker(Integer pid,String pname) implements MyInter1{
    
    
    @Override
    public void eat() {
    
    

    }
}

2. Hidden classes

This proposal improves the efficiency of all languages ​​on the JVM by enabling a standard API to define hidden classes that are undiscoverable and have limited lifetime. Frameworks inside and outside the JDK will be able to dynamically generate classes that can define hidden classes. Generally speaking, many languages ​​​​based on the JVM have mechanisms for dynamically generating classes, which can improve the flexibility and efficiency of the language.

  • Hidden classes are designed for the framework, and internal classes are generated at runtime.
  • Hidden classes can only be accessed through reflection and cannot be directly accessed by the bytecode of other classes.
  • Hidden classes can be loaded and unloaded independently of other classes, which can reduce the memory footprint of the framework

What is Hidden Class?

A class that cannot be directly used by the binary code of other classes. It is mainly used by some frameworks to generate runtime classes, but these classes cannot be used directly and are called through reflection.

For example, the lambda expression introduced in JDK8 will not be converted into a special class during compilation. Instead, the corresponding bytecode will be dynamically generated into the corresponding class object at runtime.

In addition, using dynamic proxies can also generate new dynamic classes for certain classes.

What are the characteristics of such a dynamic class?

  • Undiscoverability. Because we are dynamically generating dynamic classes for some static classes, we want this dynamically generated class to be regarded as part of the static class, so we do not want other mechanisms to discover it except the static class.
  • Access control. We hope to control dynamically generated classes while accessing static classes.
  • Life cycle. The declaration cycle of dynamically generated classes is generally shorter. We do not need to save it consistent with the life cycle of static classes.

API support

Therefore, we need some APIs to define hidden classes that cannot be discovered and have limited declaration cycles, which will help improve the efficiency of JVM-based language implementation. For example

java.lang.reflect.Proxy can define hidden classes as proxy classes that implement the proxy interface

java.lang.invoke.StringConcatFactory can generate hidden classes to save constant connection methods

java.lang.invoke.LambdaMetaFactory can generate hidden nestmate classes to house lambda bodies that access enclosing variables

Normal classes are created by calling ClassLoader::defineClass, while hidden classes are created by calling Lookup::defineHiddenClass, which takes the bytes provided by the JVM and derives a hidden class, links to that hidden class, and returns reflection to the hidden class. Accessed search object, the calling program can obtain the Class object of the hidden class through the returned search object

3.instanceof pattern matching (preview)

Instanceof pattern matching was introduced as a preview language feature in JAVA 14. It was previewed for the second time in JAVA15 without any changes. Just review JAVA14.

4.Records(preview)

Records were introduced in JDK14. Using only one Records, you can easily create a constant class, which is a transparent holding class for data, simplifying the creation syntax of classes dedicated to storing data.

When declaring a Record, the class will automatically obtain the content

  • The simple way to obtain member variables is the get method. The get method will be simplified to a method with the same name as the member variable.
  • An implementation of equals
  • Implementation of a hashcode
  • A reappearance of toString
  • A fully parameterized constructor
  • Corresponds to all final-modified member variables declared

5. Text block (OK)

JAVA13 began to introduce text blocks, JAVA14 conducted a second preview, and became a formal standard in JAVA15. Please refer to the review of text blocks in JAVA14

3. About virtual machines

1.ZGC function (OK)

JEP377:ZGC:A Scalable Low_Latency Garbage Collector ZGC function becomes a formal standard

ZGC is a new garbage collector introduced in JAVA11. It has gone through many stages. Since it finally became a formal feature in 2008, ZGC has added many improvements, such as concurrent class unloading, cancellation of unused memory, and shared class data. Supports NUMA awareness. In addition, the maximum heap has been increased from 4T to 16T. Supported platforms include Linux, Windows and MacOS. ZGC is a redesigned concurrent garbage collector that improves performance through GC pause time, but this is not a replacement for the default G1 garbage collector, but before it required -XX:+UnlockExperimentalVMOptions -XX:+UseZGC, now you only need -XX:+UseZGC. I believe it will become the default garbage collector in the near future.

The relevant parameters are:

ZAllocationSpikeTolerance ZCollectionInterval ZFragmentationLimit ZMarkStackSpaceLimit ZProcative ZUncommit ZunCommitDelay ZGC-specific JFR events(ZAllocationStall ZPageAllocation ZPageCacheFlush ZRelocationSet ZRelocationSetGroup Zuncommit ) 也从experimental变为product

2.ShenandoahGC garbage collection algorithm corrected

The Shenandoah garbage collection algorithm finally transitions from an experimental feature to a production feature

This is a recycling algorithm introduced in JAVA12, which reduces GC pause time by simultaneously performing evacuation work on running JAVA threads. Shenandoah's pause time is independent of the heap size, whether it is 200M or 200G, it will have a consistent pause time.

Comparison between Shenandoah and ZGC

  • Same: Performance is almost considered to be the same
  • Difference: ZGC is from OracleJDK, while Shenandoah only exists in OpenJDK, so you need to pay attention to the JDK version when using it.

Use the -XX:+UseShenandoahGC command line parameter to open

Shenandoah was introduced as experimental in JDK12 and became Production in JDK15. Before, it needed to pass -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC. Now it only needs -XX:+UseShenandoahGC.

Four other changes

1.edDSA signature algorithm

Edwards-Curve Digital Signature Algorithm Digital Curve Signature Algorithm

This is a new feature based on the EdWardS-Curve digital signature algorithm. Compared with the existing signature scheme in the JDK, EdDSA has higher security and performance, so it has attracted much attention. It has been encrypted in OpenSSL and BoringSSL etc. It is supported in the library and is widely used in the blockchain field.

EdDSA is a modern elliptic curve scheme that has the advantages of existing signature schemes in the JDK. EdDSA will only be implemented in the SunECMA provision

2. Disable bias locking

Disable biased locking by default, and deprecate all related command options. The goal is to determine whether the high-maintenance legacy synchronization optimization that requires continued support for biased locking is needed. The HotSpot virtual machine uses this optimization to reduce the overhead of non-contention locks. Although some JAVA applications may experience performance degradation after disabling biased locking, the performance improvement of biased locking is usually not as obvious as before.

This feature disables biased locking by default (-XX:+UseBisaedLocking) and discards all related command line options (BiasedLockingStartupDelay, BiasedLockingBulkRebiasThreshold, BiasedLockingBulkRevokeThreshold, BiasedLockingDecayTime, UseOptoBiasInlining, PrintBisasedLockingStatistics and PrintPreciseBiasedLocking Statistics)

3. Reimplement SocketAPI

As a follow-up to JEP353, this scheme reimplements the legacy socket API. The current implementation of java.net.datagram.Socket and java.netMulticastSocket dates back to JDK1.0, when IPV6 was still in development. Therefore, the current socket The interface implementation attempts to reconcile IPv4 and IPv6 in a way that is difficult to maintain.

  • Reimplement the old DatagramSocket API by replacing the base implementation of java.net.datagram
  • Change java.net.DatagramSocket and java.net.MulticastSocket to simpler, modern underlying implementations, improving the maintainability and stability of the JDK

4.External storage API

The purpose is to introduce an API to allow Java programs to safely and efficiently access external memory outside of JAVA, such as the native, persistent and managed heap.

There are many JAVA programs that access external memory, such as Ignite and MapDBb. This API will help avoid the costs associated with garbage collection and the unpredictability associated with sharing memory across processes and serializing and deserializing memory contents by mapping files to memory. The java API currently does not have a satisfactory solution for accessing external memory. But in the new proposal, the API should not break the security of the JVM

The Foreign-Memory Access API was introduced in JDK14 as the incubating API, and improved as Second Incubator in JDK15.

5. Abandonment and removal

abandoned

  • Deprecated RMI Activation For Removal

RMI Activation (delayed activation: delayed activation of objects, postponed until the first use by the customer) is marked for deletion and will be deleted in future versions. Since JAVA8 dependencies have been optional, not required. RMI Activation mechanism adds an ongoing maintenance burden, and other parts of RMI will not be deprecated for the time being.

For current applications, most of the distributed systems are based on the Web. The web server has solved the problems of traversing firewalls, filtering requests, authentication and security, and also provides many lazy loading technologies. So in modern references In programs, RMIActivation is rarely used, and it is basically missing from various open source code libraries.

In JDK8, RMI Activation was made optional, and in JDK15, it was abandoned.

  • Deprecated -XX:ForceMUMA Option, the ForceNUMA option is abandoned
  • Disable Native SunEC Implementation by Default Native SunEC Implementation is disabled by default

Remove

  • Obsolete -XX:UseAdaptiveGCBoundary, obsolete -XX:UseAdativeGCBoundary
  • Remove Solaris and SPCRC ports

In recent years, both Solaris and SPARC have been replaced by Linux operating systems and Intel processors. Dropping support for Solaris and SPARC ports will allow contributors in the OpenJDK community to accelerate the development of new features that will drive the platform forward.

  • Remove Nashorn JS engine

Nashorn is a script execution engine proposed by JDK. This function is a new feature of JDK8 released in March 2014. It has been marked as obsolete in JDK11 and has been completely removed in JDK15.

Replaced in the JDK is GraalVM. GraalVM is a runtime platform that supports Java and other Java bytecode-based languages, but also supports other languages, such as JAVAScript, Ruby, Python or LLVM. The performance is twice that of Nashorn above

JDK15 removed the Nashorn JAVAScript Engine and jjs command tool, specifically the two modules jdk.scripting.nashorn and jdk.scripting.nashorn.shell were removed.

image.png

Graal VM is an enhanced cross-language full-stack virtual machine based on hotSpot VM, which can be used as a running platform for "any language".

Guess you like

Origin blog.csdn.net/qq_28314431/article/details/132943396