Java14: New features you need to know

basic introduction

On March 17, 2020, JDK / Java 14 is officially GA (General Available). This is the fifth release since Java adopted a six-month release cycle.

This version contains more JEP Java / JDK Enhancement Proposals (JDK enhancement proposals) than Java 12 and 13 combined. A total of 16 new features, including two incubator modules, three preview features, two deprecated features, and two deleted features.

  • "Incubator Module": The APIs and tools that have not yet been finalized are first handed to the developers for use, to obtain feedback, and use these feedbacks to further improve the quality of the Java platform.
  • "Preview Feature": It is a function whose specifications have been formed and its realization has been determined, but not yet finalized. The purpose of their appearance in Java is to collect feedback information after use in the real world, and to promote the finalization of these functions. These characteristics may change at any time,According to the feedback results, these features may even be removed, but usually all preview features will eventually be fixed in Java.

Environmental preparation

Install JDK 14 https://www.oracle.com/technetwork/java/javase/overview/index.html

Install the compiler: IDEA 2020.1 or Eclipse 2020-03

Introduction of new features

JEP 305: pattern matching of instanceof (preview feature)

This feature is interesting because it opens the door for more general pattern matching. Pattern matching uses a simpler syntax to extract the components of an object based on certain conditions, and instanceof happens to be the case. It checks the object type before calling the object's method or accessing the object's fields.

Before Java 14, we used instanceof like this

@Test
public void test01() {
    Object obj = "hello java14";
    if (obj instanceof String) {
        String str = (String) obj;
        System.out.println(str.contains("hello"));
    } else {
        System.out.println("不是 String 类型");
    }
}

This is the case in Java 14, which is equivalent to simplifying the above 4 and 5 lines of code, omitting the process of forced conversion. Note: "the scope of str is still within the if structure"

@Test
public void test02() {
    Object obj = "hello java14";
    if (obj instanceof String str) {
        System.out.println(str.contains("hello"));
    } else {
        System.out.println("不是 String 类型");
    }
}

With this feature, you can reduce the number of explicit casts in Java programs to increase productivity, and you can implement more precise and concise type-safe code.

JEP 358: Very practical NullPointerException

This feature improves the readability of NullPointerException and can give more accurate information about null variables.

It was the null invented by the old man that made thousands of programmers hateful. He claimed that he had made a billion-dollar mistake, and that was the null pointer!

In "Java 8 actual combat" this is said:

  • It is the source of error. NullPointerException is currently the most typical exception in Java program development. It will inflate your code.
  • It fills your code with deeply nested null checks, and the code is extremely readable.
  • It is meaningless by itself. Null has no semantics of its own, especially it represents the modeling of missing variable values ​​in a wrong way in statically typed languages.
  • It undermines the philosophy of Java. Java has always tried to avoid making programmers aware of the existence of pointers, the only exception being: null pointers.
  • It opened a mouth in Java's type system. null does not belong to any type, which means that it can be assigned to a variable of any reference type. This can cause problems because when this variable is passed to another part of the system, you will not know what type the null variable was originally assigned to.

Optional was introduced in Java 8, and Optional makes a layer of encapsulation on objects that may be null, forcing you to think about the situation where the value does not exist, so that
you can avoid potential null pointer exceptions.

In Java 14, there is an enhancement to NPE, this feature can better prompt where the null pointer appears

We need to add on the operating parameters -XX:+ShowCodeDetailsInExceptionMessagesturn this feature on, this applies not only to enhance the characteristics of the method calls, as long as the place can cause NullPointerException also apply, including access and assignment of access field, the array.

JEP 359: Record (Preview feature)

Sometimes we need to write a lot of low-value repeated code to implement a simple data carrier class: constructor, accessor, equals (), hashCode (), toString (), etc. To avoid this duplication of code, Java 14 introduced record.

The preview feature provides a more compact syntax for declaring classes. It is worth mentioning that this feature can greatly reduce the boilerplate code required when defining similar data types.

Use record to reduce the class declaration syntax, the effect is similar to lombok's @Data annotation, data class in Kotlin. What they have in common is that some or all of the state of the class can be directly described in the class header , and this class contains only pure data.

We declare a class of record type

public record Person(String name, Integer age) {
}

Its compiled class file is as follows

public final class Person extends java.lang.Record {
    private final java.lang.String name;
    private final java.lang.Integer age;

    public Person(java.lang.String name, java.lang.Integer age) { /* compiled code */ }

    public java.lang.String toString() { /* compiled code */ }

    public final int hashCode() { /* compiled code */ }

    public final boolean equals(java.lang.Object o) { /* compiled code */ }

    public java.lang.String name() { /* compiled code */ }

    public java.lang.Integer age() { /* compiled code */ }
}

When calling its attributes, it is different from ordinary classes

@Test
public void test3(){
    Person person = new Person("张三", 12);
    person.name();
    person.age();
}

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 of name () and partner (). Note that it is different from our usual getter.
  • An implementation of an equals method that compares all member properties of the class when performing a comparison
  • Rewriting equals, of course, rewriting hashCode
  • A toString method that can print all member properties of this class.
  • Please note that there will be only one constructor.

Like enumerated types, records are a restricted form of classes . In return, the recorded object provides significant benefits in terms of simplicity.

But need to pay attention:

  • You can define static fields, static methods, constructors, or instance methods in the class declared by Record.
  • The instance field cannot be defined in the class declared by Record; the class cannot be declared as abstract; the explicit parent class cannot be declared.

JEP 361: switch expression

This is a preview feature in JDK 12 and JDK 13, and it is now an official feature.

We use ->instead of the previous :and break, additionally provided yieldto block the return value

Code demo:

public class SwitchExpression {
    public static void main(String[] args) {
        Season type = Season.AUTUMN;
        String s = switch (type) {
            case SPRING -> "春";
            case SUMMER -> "夏";
            case AUTUMN -> "秋";
            case WINTER -> "冬";
            default -> {
                System.out.println("没有" + type + "这个选项");
                yield "error";
            }
        };
    }
    enum Season {
        SPRING, SUMMER, AUTUMN, WINTER
    }
}

JEP 368: Text block (Preview second edition)

In Java, it is usually necessary to use the String type to express strings in the format of HTML XML SQL or JSON, etc. When performing string assignment, you need to escape and concatenate before compiling the code, but this expression is difficult to read and difficult maintain.

So text blocks were introduced in JDK13, a second round of preview was conducted in JDK 14, and the JDK14 version mainly added two functions, namely \and\s

For example, we want to write a sql statement, using ordinary strings like this. This is a relatively simple statement.

@Test
public void test1() {
    String sql =
        "SELECT name, age\n" +
        "FROM user\n" +
        "WHERE age = 19";
    System.out.println(sql);
}

The use of code blocks is like this, the readability becomes higher

@Test
public void test2(){
    String sql = """
            SELECT name, age
            FROM user
            WHERE age = 19
            """;
    System.out.println(sql);
}

But by running the above code, we can see that what format is written in the code block will output what format, if we want it to output only one line, it is also readable?

At this time, we can use the new \(cancel line break) and \s(a space) added by JDK 14

@Test
public void test3(){
    String sql = """
            SELECT name, age \
            FROM user\s\
            WHERE age = 19\s\
            """;
    System.out.println(sql);
}

JEP 366: ParallelScavenge and SerialOld GC combination deprecated

The JDK official gave the reason for marking this GC combination as Deprecate: this GC combination requires a lot of code maintenance work, and this GC combination is rarely used. Because its usage scenario should be a large Young area with a small Old area. In this case, we can barely accept the pause time when the Old area uses SerialOldGC to collect.

Abandoned parallel young generation GC in combination with the SerialOld GC (XX: + UseParallelGC and XX: UseParallelOldGC mating opening), now -XX:+UseParallelGC -XX:-UseParallelOldGCor -XX:-UseParallelOldGCwill appear the following warning:

Java HotSpot(TM) 64 Bit Server VM warning: Option UseParallelOldGC was deprecated in version 14.0 and will likely be removed in a future release.

JEP 363: Remove the CMS garbage collector

The coming general meeting has come, since G1 was born based on Region), CMS was marked as Deprecate in JDK9 (JEP 291: Deprecate the Concurrent Mark Sweep (CMS) Garbage Collector)

Disadvantages of CMS:

  1. Memory fragmentation will occur, resulting in insufficient space available for user threads after concurrent cleanup.
  2. Now that Concurrency is emphasized, the CMS collector is very sensitive to CPU resources.
  3. CMS collector cannot handle floating garbage

The above problems, especially the fragmentation problem, give your JVM instance like a bomb. Maybe you will come to FGC at the peak of your business. When the CMS stops working, Serial Old GC will be used as an alternative, and Serial Old GC is the worst performing garbage collection method in the JVM. A pause of a few seconds or even ten seconds is possible.

CMS removed garbage collector, if used in JDK14 XX:+UseConcMarkSweepGCwords, JVM does not complain, just give a warning message.

JEP:ZGC on macOS and windows

First look at the horrible performance of ZGC. It can achieve low latency of garbage collection at any arbitrary heap size under the premise of not affecting the throughput as much as possible.

JEP 364: ZGC application on macOS, JEP 365: ZGC application on Windows

Before JDK14, ZGC was only supported by Linux. Although many users who use ZGC use a Linux-like environment, on Windows and macOS, people also need ZGC for development, deployment, and testing. Many desktop applications can also benefit from ZGC. Therefore, the ZGC feature was ported to Windows and macOS.

How to use:-XX:+UnlockExperimentalVMOptions -XX:+UseZGC

Although ZGC is still in the experimental state and has not completed all the features, but the performance has been quite dazzling at this time, it is not too much to describe it as "shocking and revolutionary". The future will be the garbage collector of choice for applications on the server side, large memory, and low latency.


There are a few unimportant new features not listed, you can check the relevant information by yourself

Most of the information in this article comes from this video courseware: https://www.bilibili.com/video/BV1tC4y147US

Guess you like

Origin www.cnblogs.com/songjilong/p/12722229.html