Introduction to new features of Java 14

Don't make a title party, write an article seriously.
The article has been included in Github.com/niumoo/JavaNotes and Unread code blog , pay attention and don't get lost.

Java 14 has been released as early as September 2019. Although it is not a long supported version, it also brings many new functions.

Java 14 official download: https://jdk.java.net/archive/

Java 14 official documentation: https://openjdk.java.net/projects/jdk/14/

Java 14 new features:

  • 305: instanceof type judgment (Preview)
  • 343: packaging tools (incubation)
  • 345: G1 supports NUMA (non-uniform memory access)
  • 358: more useful NullPointerExceptions
  • 359: Records (Preview)
  • 361: Switch expression (standard)
  • 362: obsolete Solaris and SPARC port support
  • 363: removing CMS garbage collector
  • 364: ZGC for MacOS
  • 365: ZGC for windows
  • 366: discarding ParallelScavenge + SerialOld GC combination
  • 367: removing Pack200 Tools and API s
  • 368: text block (second preview)
  • 370: Foreign-Memory Access API (Incubator)
  • 349: JFR Event Streaming
  • 352: Non-Volatile Mapped Byte Buffers

Note: if a function is a preview version, you need to turn on the preview function when compiling and running.

./javac --enable-preview --release 14 Test.java
./java --enable-preview Test

This article belongs to New Java features tutorial Series, which will introduce the new functions of each version of Java. You can click to browse.

1. JEP 305: instanceof type judgment (Preview)

Before Java 14, after using instanceof for type judgment, object type conversion is required before use.

package com.wdbyte;

import java.util.ArrayList;
import java.util.List;

public class Java14BeaforInstanceof {

    public static void main(String[] args) {
        Object obj = new ArrayList<>();
        if (obj instanceof ArrayList) {
            ArrayList list = (ArrayList)obj;
            list.add("www.wdbyte.com");
        }
        System.out.println(obj);
    }
}

In Java 14, the variable name can be specified for type conversion when judging the type, which is convenient for use.

package com.wdbyte;

import java.util.ArrayList;

public class Java14Instanceof {
    public static void main(String[] args) {
        Object obj = new ArrayList<>();
        if (obj instanceof ArrayList list) {
            list.add("www.wdbyte.com");
        }
        System.out.println(obj);
    }
}

You can see that after using instanceof to judge whether the type is valid, the type will be automatically cast to the specified type.

Output results:

[www.wdbyte.com]

This feature is also a preview function in Java 14 and officially becomes a regular in Java 16.

2. JEP 343: Packaging Tool (incubation)

In Java 14, a packaging tool is introduced. The command is jpackage. Using jpackage command, JAR packages can be packaged into software formats supported by different operating systems.

jpackage --name myapp --input lib --main-jar main.jar --main-class myapp.Main

Common platform formats are as follows:

  1. Linux: deb and rpm
  2. macOS: pkg and dmg
  3. Windows: msi and exe

It should be noted that jpackage does not support cross compilation, that is, it cannot be packaged into the software format of Mac OS or Linux system on windows platform.

3. JEP 345: G1 supports NUMA (non-uniform memory access)

G1 collector can now sense NUMA memory allocation mode to improve G1 performance. You can use + XX:+UseNUMA to enable this function.

Extended reading: https://openjdk.java.net/jeps/345

4. JEP 358: more useful NullPointerExceptions

NullPointerException has always been a common exception, but before Java 14, if there are multiple expressions on a line, after NULL pointers are reported, simply from the error information, you may not know which object is NULL. The following is a demonstration.

package com.wdbyte;

public class Java14NullPointerExceptions {

    public static void main(String[] args) {
        String content1 = "www.wdbyte.com";
        String content2 = null;
        int length = content1.length() + content2.length();
        System.out.println(length);
    }
}

Before Java 14, we can only get the number of lines with errors from the following error reports, but we can't determine whether content1 or content2 is null.

Exception in thread "main" java.lang.NullPointerException
	at com.alibaba.security.astralnet.console.controller.ApiChartsTest.main(Java14NullPointerExceptions.java:8)

But in Java 14, it will clearly tell you because "content2" is null.

Exception in thread "main" java.lang.NullPointerException: 
	Cannot invoke "String.length()" because "content2" is null
	at com.wdbyte.Java14NullPointerExceptions.main(Java14NullPointerExceptions.java:8)

5. JEP 359: Records (Preview)

record is a new type. It is essentially a final class. At the same time, all attributes are final modifications. It will automatically compile public get hashcode, equals, toString and other methods, reducing the amount of code.

Example: write a Dog record class to define the name and age attributes.

package com.wdbyte;

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

Use of Record.

package com.wdbyte;

public class Java14Record {

    public static void main(String[] args) {
        Dog dog1 = new Dog("Shepherd Dog", 1);
        Dog dog2 = new Dog("Pastoral dogs", 2);
        Dog dog3 = new Dog("Siberian Husky", 3);
        System.out.println(dog1);
        System.out.println(dog2);
        System.out.println(dog3);
    }
}

Output results:

Dog[name=Shepherd Dog, age=1]
Dog[name=Pastoral dogs, age=2]
Dog[name=Siberian Husky, age=3]

This function is previewed twice in Java 15 and officially released in Java 16.

6. JEP 361: Switch expression (standard)

The improvement of switch expression has been started since Java 12. Java 12 enables switch to support L - > syntax. Java 13 introduces the yield keyword to return results. However, in Java 12 and 13, the functions are preview versions, while in Java 14, they are officially confirmed.

// The season of the month is output by importing the month
public static String switchJava12(String month) {
     return switch (month) {
        case "march", "april", "may"            -> "spring";
        case "june", "july", "august"           -> "summer";
        case "september", "october", "november" -> "autumn";
        case "december", "january", "february"  -> "winter";
        default -> "month erro";
    };
}
// The season of the month is output by importing the month
public static String switchJava13(String month) {
    return switch (month) {
        case "march", "april", "may":
            yield "spring";
        case "june", "july", "august":
            yield "summer";
        case "september", "october", "november":
            yield "autumn";
        case "december", "january", "february":
            yield "winter";
        default:
            yield "month error";
    };
}

Extended reading: Introduction to new features of Java 12Introduction to new features of Java 13JEP 325: Switch expression

7. JEP 368: text block (second preview)

Text block is a syntax introduced by Java 13 and enhanced in Java 14. The text block is still the preview function. This update adds two escape characters.

  1. \No wrapping at the end
  2. \s represents a space

Example: text block experience

String content = """
        {
            "upperSummary": null,\
            "sensitiveTypeList": null,
            "gmtModified": "2011-08-05\s10:50:09",
        }
         """;
System.out.println(content);

Output results:

{
    "upperSummary": null,    "sensitiveTypeList": null,
    "gmtModified": "2011-08-05 10:50:09",
}

The text block function was officially released in Java 15.

Other updates

JEP 362: obsolete Solaris and SPARC port support

Starting from Java 14, give up support for Solaris/SPARC, Solaris/x64, and Linux/SPARC ports, and give up some development, which is bound to speed up the overall development pace of Java.

Related reading: https://openjdk.java.net/jeps/362

JEP 363: removing CMS garbage collector

Removing the support for CMS (Concurrent Mark Sweep) garbage collector actually started removing CMS garbage collector as early as Java 9, but it was officially deleted in Java 14.

JEP 364: ZGC on macOS (experimental)

Java 11 introduced the Z garbage collector (ZGC) on Linux, which can now be ported to macOS.

JEP 365: ZGC on Windows (experimental)

Java 11 introduced the Z garbage collector (ZGC) on Linux, and now it can be ported to Windows (version greater than 1803).

JEP 366: discard ParallelScavenge + SerialOld GC combination

Because there are few usage scenarios and the maintenance work is too large, it is abandoned. Related reading: https://openjdk.java.net/jeps/366

JEP 367: removing Pack200 tools and API s

reference resources

  1. https://openjdk.java.net/projects/jdk/14/
  2. https://openjdk.java.net/jeps/366
  3. https://openjdk.java.net/jeps/362
  4. New Java features tutorial

Hello world 😃

I'm Alan, a technical tool man who carries bricks every day.

If you want to subscribe, you can follow The official account is "unread code". , or Unread code blog , or Add wechat (wn8398).

This article has also been sorted to GitHub.com/niumoo/JavaNotes Welcome, Star.

Keywords: Java

Added by ecco on Sun, 26 Dec 2021 20:22:53 +0200