Talking about the new features of java15

You can do whatever you want, I use Java8 . 

Not to mention the installation of jdk15 and the installation of the new version of idea, here are two software.

Link: https://pan.baidu.com/s/1hOb0CChSfYotFl3s3QL2yA  Password: mp6a

After the installation is complete, check the version with java -version to confirm that the environment is correct.

The new version of idea requires additional settings as follows.

ok, the environment is ok, start coding.

The main features of this release are: 

Java 15 provides users with 14 major enhancements/changes, including an incubator module, three preview functions, two deprecated functions, and two delete functions. 

http://openjdk.java.net/projects/jdk/15/ 

Corresponding Chinese features: (JEP: JDK Enhancement Proposals, JDK enhancement suggestions, that is, JDK feature addition and improvement proposals.) 

  • JEP 339: EdDSA Digital Signature Algorithm 
  • JEP 360: Sealed Class (Preview) 
  • JEP 371: Hidden Class 
  • JEP 372: Remove the Nashorn JavaScript engine 
  • JEP 373: Reimplement the Legacy DatagramSocket API 
  • JEP 374: Disable Bias Lock 
  • JEP 375: instanceof pattern matching (second preview) 
  • JEP 377: ZGC: A Scalable Low-Latency Garbage Collector 
  • JEP 378: Text Block 
  • JEP 379: Shenandoah: Low Pause Time Garbage Collector 
  • JEP 381: Remove Solaris and SPARC ports 
  • JEP 383: External Memory Access API (Second Incubation Edition) 
  • JEP 384: Records (second preview) 
  • JEP 385: Abandoning the RMI activation mechanism 

to sum up: 

  • Gangster borrow the words: JDK15 whole new characteristics is not very rosy, it is mainly the previous version preview feature, function did determine, such as text blocks, ZGC, etc., that way we can safely use Up. 

Why does the boss say that this new feature is not very eye-catching? The main features this time are the following six:

JEP 360: Sealed class (preview),  (this concept is not actually the first of the java language, other languages ​​have been mentioned before)

JEP 371: Hidden classes,                  (this concept is not actually the first of the java language, other languages ​​have been mentioned before)

JEP 375: instanceof pattern matching (second preview),

JEP 384: Records (second preview)

JEP 377: ZGC: an extensible low-latency garbage collector,   (previous features are corrected)

JEP 378: Text block,    (previous function correction)

1. JEP 360: Sealed Classes (Preview) sealed classes and interfaces (preview) 

        Used to restrict the use of superclasses, sealed classes and interfaces restrict other classes or interfaces that may inherit or implement them.

        Specific use: 

        Because we have introduced sealed classes or interfaces, these classes or interfaces only allow the specified classes or interfaces to be extended and implemented. 

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

        Our code was like this before. 

public class Person { } //人

class Teacher extends Person { }//教师

class Worker extends Person { }  //工人

class Student extends Person{ } //学生

But we now want to restrict the Person class to only be inherited by these three classes and not be inherited by other classes. This is what we need to do.

//添加sealed参数,permits后面跟上只能被继承的子类名称
public sealed class Person permits  Teacher, Worker, Student{ } //人

//子类可以被修饰为 final
final class Teacher extends Person { }//教师

//子类可以被修饰为 non-sealed,此时 Worker类就成了普通类,谁都可以继承它
non-sealed class Worker extends Person { }  //工人
//任何类都可以继承Worker
class AnyClass extends Worker{}

//子类可以被修饰为 sealed,同上
sealed class Student extends Person permits MiddleSchoolStudent,GraduateStudent{ } //学生


final class MiddleSchoolStudent extends Student { }  //中学生

final class GraduateStudent extends Student { }  //研究生

A very powerful and practical feature that can limit the hierarchy of classes.

Two, JEP 371: Hidden Classes ( hidden class ) 

The proposal uses standard APIs to define hidden classes that cannot be discovered and have a limited life cycle, thereby improving the efficiency of all languages ​​on the JVM. Frameworks inside and outside the JDK will be able to dynamically generate classes, and these classes can define hidden classes. Generally speaking, many languages ​​based on JVM have a mechanism for dynamically generating classes, which can improve the flexibility and efficiency of the language. 

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

What are Hidden Classes? 

Hidden Classes are classes that cannot be directly used by the binary code of other classes. Hidden Classes are mainly used by some frameworks to generate runtime classes, but these classes are not used directly, but are called through reflection mechanisms. 

For example, the lambda expression introduced in JDK8, the JVM will not convert the lambda expression into a special class at compile time, but dynamically generate the corresponding class object from the corresponding bytecode at runtime. 

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

  So what characteristics do we hope these dynamically generated classes need to have? 

  1. Undiscoverable. Because we are dynamically generated dynamic classes for certain static classes, we hope to regard this dynamically generated class as part of the static class. So we don't want other mechanisms other than the static class to be discovered. 
  1. Access control. We hope that while accessing and controlling static classes, we can also control dynamically generated classes. 
  1. Life cycle. The life cycle of dynamically generated classes is generally relatively short, and we don't need to keep it consistent with the life cycle of static classes. 

API support 

So we need some APIs to define hidden classes that cannot be discovered and have a limited life cycle. This will improve the efficiency of all JVM-based language implementations. 

such as: 

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

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

java.lang.invoke.LambdaMetaFactory can generate hidden nestmate classes to accommodate lambda subjects that access closed variables; 

Ordinary classes are created by calling ClassLoader::defineClass, and hidden classes are created by calling Lookup::defineHiddenClass. This allows the JVM to derive a hidden class from the provided bytes, link the hidden class, and return a lookup object that provides reflective access to the hidden class. The calling program can obtain the Class object of the hidden class through the returned search object. 

Three, Pattern Matching for instanceof (Second Preview) instanceof automatic matching pattern 

The instanceof pattern matching introduced as a preview language feature in Java 14 is in the second preview in Java 15 without any changes.

I wrote about this feature in the new features of java14, please refer to: new features of java14

Old writing: 

// 先判断类型
if (obj instanceof String) { 
    // 然后转换 
    String s = (String) obj; 
    // 然后才能使用 
} 

New wording: ( automatic matching mode) 

if (obj instanceof String s) {
    // 如果类型匹配 直接使用 
} else { 
    // 如果类型不匹配则不能直接使用 
} 

Fourth, ZGC: A Scalable Low-Latency Garbage Collector (Production)  ZGC function is turned positive 

Friends who are concerned about low-level optimization can pay more attention to this. For more, please see more of new features of java14-ZGC

ZGC is a new garbage collector introduced by Java 11 (the default garbage collector after JDK9 is G1). After several experimental stages, it has finally become an official feature. 

Since 2018, ZGC has added many improvements, from concurrent class unloading, elimination of unused memory, support for class data sharing, to improved NUMA awareness. In addition, the maximum heap size has been increased from 4 TB to 16 TB. Supported platforms include Linux, Windows and MacOS. 

ZGC is a redesigned concurrent garbage collector that improves performance by reducing GC pause time

But this is not to replace the default GC, the default GC is still G1 ; previously you need to enable ZGC through -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, ZProactive, ZUncommit, ZUncommitDelay ZGC-specific JFR events (ZAllocationStall, ZPageAllocation, ZPageCacheFlush, ZRelocationSet, ZRelocationSetGroup, ZUncommit) are also changed from experimental to product.

V. JEP 378 : Text block function is corrected 

Text Blocks first appeared in JDK 13 as a preview function, and then previewed again in JDK 14, and finally it was confirmed in JDK 15 and can be used with confidence. 

I have written it before when I wrote java14, the main meaning is that you can throw sql, html, json, and articles directly into """ """. Keep the previous format. It should be noted that length will have one extra at the end. Spaces wrap. take a peek

package com.hermanwang.java1;

import org.junit.Test;

/**
 * @author hermanwang
 * @create 2020-10-24
 */
public class TextBlocksTest {
    @Test
    public void test1(){
        // 之前的写法
        String text1 = "The Sound of silence\n" +
                "Hello darkness, my old friend\n" +
                "I've come to talk with you again\n" +
                "Because a vision softly creeping\n" +
                "Left its seeds while I was sleeping\n" +
                "And the vision that was planted in my brain\n" +
                "Still remains\n" +
                "Within the sound of silence";

        System.out.println(text1);

        //jdk13中的新特性:
        String text2 = """
                The Sound of silence
                Hello darkness, my old friend
                I've come to talk with you again
                Because a vision softly creeping
                Left its seeds while I was sleeping
                And the vision that was planted in my brain
                Still remains
                Within the sound of silence\
                """;
        System.out.println();
        System.out.println(text2);

        System.out.println(text1.length());
        System.out.println(text2.length());
    }

    //html
    @Test
    public void test2(){
        String html1 = "<html lang=\"en\">\n" +
                "<head>\n" +
                "    <meta charset=\"UTF-8\">\n" +
                "    <title>java14新特性</title>\n" +
                "</head>\n" +
                "<body>\n" +
                "    <p>hello,atguigu</p>\n" +
                "</body>\n" +
                "</html>";
        //jdk13中的新特性:
        String html2 = """
                <html lang="en">
                <head>
                    <meta charset="UTF-8">
                    <title>java14新特性</title>
                </head>
                <body>
                    <p>hello,atguigu</p>
                </body>
                </html>
                """;
    }

    //json
    @Test
    public void test3() {
        //jdk13之前的写法
        String myJson = "{\n" +
                "    \"name\":\"Song Hongkang\",\n" +
                "     \"address\":\"www.atguigu.com\",\n" +
                "    \"email\":\"[email protected]\"\n" +
                "}";
        System.out.println(myJson);

        //jdk13的新特性
        String myJson1 = """
                {
                    "name":"Song Hongkang",
                     "address":"www.atguigu.com",
                    "email":"[email protected]"
                }""";
        System.out.println(myJson1);
    }

    //sql
    @Test
    public void test4(){
        String sql = "SELECT id,NAME,email\n" +
                "FROM customers\n" +
                "WHERE id > 4\n" +
                "ORDER BY email DESC";

        //jdk13新特性:
        String sql1 = """
                SELECT id,NAME,email
                FROM customers
                WHERE id > 4
                ORDER BY email DESC
                """;
    }
    //jdk14新特性
    @Test
    public void test5(){
        String sql1 = """
                SELECT id,NAME,email
                FROM customers
                WHERE id > 4
                ORDER BY email DESC
                """;
        System.out.println(sql1);

        // \:取消换行操作
        // \s:表示一个空格
        String sql2 = """
                SELECT id,NAME,email \
                FROM customers\s\
                WHERE id > 4 \
                ORDER BY email DESC\
                """;
        System.out.println(sql2);
        System.out.println(sql2.length());
    }
}

6. JEP 384 : Records Class (Preview) 

Records Class is also the second preview function that appears. It also appeared once in JDK 14. It is more convenient to create a constant class by using Record. The comparison of the before and after code is as follows.  

  • When you declare a class with Record, the class will automatically have the following functions: 
  • A simple way to get member variables, take the above code as an example name() and partner(). Note that it is different from our usual getter writing. 
  • An implementation of the equals method that compares all member attributes of the class when performing comparison 
  • Rewriting equals of course requires rewriting hashCode 
  • A toString method that can print all the member properties of the class. 
  • Please note that there will only be one constructor.

Old writing:

package com.hermanwang.java1;

import java.util.Objects;

public class Point {

        private final int x;
        private final int y;
        Point(int x, int y) {
            this.x = x;
            this.y = y;
        }
        int x() {
            return x;
        }
        int y() {
            return y;
        }
        public boolean equals(Object o) {
            if (!(o instanceof Point))
                return false;
            Point other = (Point) o;
            return other.x == x && other.y == y;
        }

        public int hashCode() {
            return Objects.hash(x, y);
        }
        public String toString() {
            return String.format("Point[x=%d,y=%d]", x,y);
        }
}

New writing: 

record Point(int x, int y) {} 

Other features of record are as follows:

package com.hermanwang.java1;

/**
 * @author hermanwang
 * @create 2020-10-24
 */
public record Customer(String name,Customer partner) {
    //还可以声明构造器、静态的变量、静态的方法、实例方法

    public Customer(String name){
        this(name,null);
    }

    public static String info;

    public static void show(){
        System.out.println("我是一个客户");
    }

    public void showName(){
        System.out.println("我的名字是:" + name());
    }

    //不可以在Record中定义实例变量
//    public int id;

}

//Record不可以声明为abstract的
//abstract record User(){}

//Record不可以显式的继承于其他类
//record User() extends Thread{}

Okay, so far, the main six new features have been completed, and the remaining eight are not very important new features.

Just understand the following characteristics.

Seven, JEP 339 : Edwards-Curve Digital Signature Algorithm ( EdDSA digital signature algorithm ) 

This is a new feature. 

A newly added encryption signature based on the Edwards-Curve digital signature algorithm (EdDSA-Edwards-Curve Digital Signature Algorithm), that is, the Edwards curve digital signature algorithm. It is supported in many other encryption libraries (such as OpenSSL and BoringSSL). 

Compared with the existing signature scheme in the JDK, EdDSA has higher security and performance, so it has attracted much attention. It has been supported in encryption libraries such as OpenSSL and BoringSSL, and is used more in the blockchain field. 

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

Eight, JEP 373: Reimplement the Legacy DatagramSocket API ( reimplement DatagramSocket API) 

The new plan is a follow-up to JEP 353, which re-implements the legacy socket API. 

The current implementation of java.net.datagram.Socket and java.net.MulticastSocket can be traced back to JDK 1.0 when IPv6 was still under development. Therefore, current multicast socket implementations try to reconcile the difficult-to-maintain ways of IPv4 and IPv6. 

  • Re-implement the old DatagramSocket API by replacing the basic implementation of java.net.datagram. 
  • Change java.net.DatagramSocket and java.net.MulticastSocket to simpler and more modern low-level implementations. Improve the maintainability and stability of the JDK. 

Re-implement the legacy DatagramSocket API by replacing the underlying implementation of java.net.datagram.Socket and java.net.MulticastSocket API with simpler and more modern implementations. 

New implementation: 1. Easy to debug and maintain; 2. Cooperate with the virtual thread being explored in Project Loom.

Nine, JEP 374: Disable and Deprecate Biased Locking disabled tend to lock 

 By default, bias locking is disabled and all related command-line options are deprecated. The goal is to determine whether it is necessary to continue to support the high maintenance cost legacy synchronization optimization of biased locking. The HotSpot virtual machine uses this optimization to reduce the overhead of non-competitive locking. Although some Java applications may experience performance degradation after disabling biased locks, the performance improvement of biased locks is usually not as obvious as before. 

This feature disables biased locking by default (-XX:+UseBiasedLocking), and discards all related command line selections (BiasedLockingStartupDelay, BiasedLockingBulkRebiasThreshold, BiasedLockingBulkRevokeThreshold, BiasedLockingDecayTime, UseOptoBiasInliningStatistics and PrintBiasedLockStatistics and PrintBiasedLockPrelining) 

10. JEP 379: Shenandoah: Low Pause Time Garbage Collector 

The Shenandoah garbage collection algorithm finally changed from an experimental feature to a product feature. This is a collection algorithm introduced from JDK 12, which reduces the GC pause time by evacuation work with the running Java thread at the same time. Shenandoah's pause time has nothing to do with the heap size, regardless of whether the stack is 200 MB or 200 GB, it has the same consistent pause time. 

How to describe the relationship between Shenandoah and ZGC? The similarities and differences are as follows: 

  • Similarities: performance can be considered almost the same 
  • Difference: ZGC is Oracle JDK. Shenandoah only exists in OpenJDK, so you need to pay attention to your JDK version when using 

Open method: use -XX:+UseShenandoahGC command line parameter to open. 

Shenandoah was introduced as experimental in JDK12, and became Production in JDK15; previously it needed to be enabled through -XX:+UnlockExperimentalVMOptions -XX:+UseShenandoahGC, now it only needs -XX:+UseShenandoahGC to enable 

11. JEP 383: Foreign-Memory Access API  External Memory Access API (Incubator Edition) 

The purpose is to introduce an API to allow Java programs to safely and effectively access external memory outside the Java heap. Such as native, persistent and managed heaps. 

There are many Java programs that access external memory, such as Ignite and MapDB. The 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 provide a satisfactory solution for accessing external memory. But in the new proposal, the API should not undermine the security of the JVM. 

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

12. JEP 381 : Remove the Solaris and SPARC Ports ( Remove Solaris and SPARC Ports ) 

The source code and build support for Solaris/SPARC, Solaris/x64, and Linux/SPARC ports were deleted, which was marked as obsolete in JDK 14, and officially removed in JDK15. Many projects and features under development (such as Valhalla, Loom, and Panama) require major changes to adapt to the CPU architecture and operating system specific code. 

In recent years, both Solaris and SPARC have been replaced by Linux operating systems and Intel processors. Giving up support for Solaris and SPARC ports will enable contributors in the OpenJDK community to accelerate the development of new features, thereby pushing the platform forward. 

十三、JEP 372Remove the Nashorn JavaScript Engine  

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

GraalVM is replaced in JDK11. 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 more than twice that of Nashorn. 

JDK15 removed the Nashorn JavaScript Engine and jjs command line tool. Specifically, the two modules jdk.scripting.nashorn and jdk.scripting.nashorn.shell have been removed. 

十四、JEP 385:Deprecate RMI Activation for Removal 

RMI Activation is marked as Deprecate and will be deleted in a future version. The RMI activation mechanism is an obsolete part of RMI and has been optional rather than mandatory since Java 8. The RMI activation mechanism increases the ongoing maintenance burden. Other parts of RMI will not be deprecated for the time being. 

RMI jdk1.2 is introduced, EJB is in the RMI system, we use delayed activation. Delayed activation defers the activation of the object until the client uses it for the first time (that is, the first method call). Since RMI Activation is so easy to use, why should it be discarded? 

Because for modern applications, most of the distributed systems are Web-based. The web server has solved the problems of traversing firewalls, filtering requests, authentication and security, and also provides many delay loading technologies. 

So in modern applications, RMI Activation has rarely been used. And in various open source code libraries, the code for using RMI Activation is basically not found. In order to reduce the maintenance cost of RMI Activation, in JDK8, RMI Activation is set as optional. Now in JDK15, it can finally be discarded. 

 

Finish. Test code address: https://github.com/cyberHermanwang/Java15Feature

 

Thank you Shang Silicon Valley!

Guess you like

Origin blog.csdn.net/cyberHerman/article/details/109253931