Java language features series

  • New features in Java5
  • New features for Java6
  • New features in Java7
  • New features in Java8
  • New features in Java9
  • New features in Java10
  • New features for Java11
  • New features in Java12
  • New features for Java13
  • New features for Java14
  • New features for Java15

sequence

This article focuses on the new features of Java14

The version number

java -version
openjdk version "14" 2020-03-17
OpenJDK Runtime Environment (build 14+36-1461)
OpenJDK 64-Bit Server VM (build 14+36-1461, mixed mode, sharing)
Copy the code

The version information shows that it is Build 14+36

Feature list

305:Pattern Matching for instanceof (Preview)

JDK14 introduces the Preview version’s pattern matching for Instanceof, as shown in the following example

    public boolean isBadRequestError(Exception ex) {
        return (ex instanceof HttpClientErrorException rce) &&
                HttpStatus.BAD_REQUEST == rce.getStatusCode();
    }
Copy the code

There is no need to type force in itself

343:Packaging Tool (Incubator)

JDK14 JDK is introduced. The incubator. Jpackage. Jmod, it is based on deployment headaches javapackager tool build, aims to create a simple packaging tools, can be used to build the exe, PKG, DMG, deb, the installation of RPM files; An example of a modular app build is as follows

jpackage --name myapp --input lib --main-jar main.jar
Copy the code

345:NUMA-Aware Memory Allocation for G1

Memory allocation for NUMA-Aware was implemented to improve G1 performance on large machines

349:JFR Event Streaming

JDK11 introduces JFR, which is dumped to disk and then analyzed. In JDK14, stream is supported for continuous monitoring, as shown in the following example

public class AgentMain implements Runnable {

    public static void premain(String agentArgs, Instrumentation inst) {
        try {
            Logger.getLogger("AgentMain").log(
                    Level.INFO, "Attaching JFR Monitor");
            new Thread(new AgentMain()).start();
        } catch (Throwable t) {
            Logger.getLogger("AgentMain").log(
                    Level.SEVERE,"Unable to attach JFR Monitor", t);
        }
    }

    @Override
    public void run() {
        var sender = new JfrStreamEventSender();
        try (var rs = new RecordingStream()) {
            rs.enable("jdk.CPULoad")
                    .withPeriod(Duration.ofSeconds(1));
            rs.enable("jdk.JavaMonitorEnter")
                    .withThreshold(Duration.ofMillis(10));
            rs.onEvent("jdk.CPULoad", sender);
            rs.onEvent("jdk.JavaMonitorEnter", sender); rs.start(); }}}Copy the code

352:Non-Volatile Mapped Byte Buffers

This feature adds Java. The base/JDK/internal/misc/ExtendedMapMode Java to support MappedByteBuffer access non – volatile memory (NVM)

358:Helpful NullPointerExceptions

This feature can better prompt where a null pointer, need to pass – XX: + ShowCodeDetailsInExceptionMessages open, sample as below

public class NullPointerExample { public record City(String name){ } public record Location(City city) { } public record  User(String name, Location location) { } public static void main(String[] args){ User user = new User("hello", new Location(null)); System.out.println(user.location().city().name()); }}Copy the code

The output is as follows

Exception in thread "main" java.lang.NullPointerException: Cannot invoke "com.example.NullPointerExample$City.name()" because the return value of "com.example.NullPointerExample$Location.city()" is null
	at com.example.NullPointerExample.main(NullPointerExample.java:25)
Copy the code

359:Records (Preview)

JDK14 introduces the Record type in the Preview version, as shown in the following example

public record Point(int x, int y) {

    public Point {
        System.out.println(String.format("(%d,%d)", x, y));
    }

    public Point(int value) {
        this(value, value);
    }

    public static Point of(int value) {
        returnnew Point(value, value); }}Copy the code

Javap decompilation follows

javac --enable-preview -source 14 Point.java
javap -verbose Point.class
Compiled from "Point.java"
public final class com.example.domain.Point extends java.lang.Record {
  public com.example.domain.Point(int, int);
  public static com.example.domain.Point of(int);
  public java.lang.String toString();
  public final int hashCode();
  public final boolean equals(java.lang.Object);
  public int x();
  public int y();
}
Copy the code

You can see that Point inherits java.lang.Record and provides final hashCode and equals via Invokedynamic

361:Switch Expressions (Standard)

-> switch in JDK14 :+break; Alternatively, yield is provided to return a value in a block, as shown in the following example

    public void testSwitchWithArrowBlockAndYield() {
        int n = 3;
        String quantityString = switch (n) {
            case1 - >"one";
            case2 - >"two";
            default -> {
                System.out.println("default");
                yield "many"; }}; System.out.println(quantityString); }Copy the code

362:Deprecate the Solaris and SPARC Ports

Deprecated Solaris/SPARC, Solaris/ X64, and Linux/SPARC ports to be removed in future releases

363:Remove the Concurrent Mark Sweep (CMS) Garbage Collector

Remove the CMS garbage collector, if you use -xx :+UseConcMarkSweepGC in JDK14, warning will appear, but the default garbage collector will run instead of exit, as shown below

OpenJDK 64-Bit Server VM warning: Ignoring option UseConcMarkSweepGC; support was removed in 14.0
Copy the code

364:ZGC on macOS

Previously ZGC was only available on Linux, but now ZGC is available on Macs, as shown below

-XX:+UnlockExperimentalVMOptions -XX:+UseZGC
Copy the code

365:ZGC on Windows

Previously ZGC was only available on Linux, but now it is available on Windows (version 1803 or older) as shown in the following example

-XX:+UnlockExperimentalVMOptions -XX:+UseZGC
Copy the code

366:Deprecate the ParallelScavenge + SerialOld GC Combination

Parallel Young Generation GC with SerialOld GC (-xx :+ UseParallelOldGC) If -xx :+UseParallelGC -xx: -useParalleloldgc or -xx: -useParalleloldgc is used, the following alarms are generated

OpenJDK 64-Bit Server VM warning: Option UseParallelOldGC was deprecated inVersion 14.0 and will likely be removedin a future release.
Copy the code

Parallel Young and Old Generation GC Algorithms -xx :+UseParallelGC

367:Remove the Pack200 Tools and API

Removed the Pack200 API

368:Text Blocks (Second Preview)

For the second preview of text blocks introduced in JDK13, two escape sequences (\ and \s escape sequence) are added in JDK14, as shown below

    @Test
    public void testTextBlockWithTwoNewEscapeSequences() {
        String inOneLine = """ Lorem ipsum dolor sit amet, consectetur adipiscing \ elit, sed do eiusmod tempor incididunt ut labore \ et dolore magna aliqua.\ """;
        System.out.println(inOneLine);

        String singleSpace = """ red \s green\s blue \s """;
        System.out.println(singleSpace);
    }
Copy the code

370:Foreign-Memory Access API (Incubator)

An incubator version of the API is provided to manipulate out-of-heap memory, as shown in the following example

    @Test
    public void testForeignMemoryAccessAPI() { SequenceLayout intArrayLayout = MemoryLayout.ofSequence(25, MemoryLayout.ofValueBits(32, ByteOrder.nativeOrder()));  VarHandle intElemHandle = intArrayLayout.varHandle(int.class, MemoryLayout.PathElement.sequenceElement()); try (MemorySegment segment = MemorySegment.allocateNative(intArrayLayout)) { MemoryAddress base = segment.baseAddress();for(int i = 0; i < intArrayLayout.elementCount().getAsLong(); i++) { intElemHandle.set(base, (long) i, i); }}}Copy the code

Details of interpretation

In addition to the major features listed above, there are also some API updates and deprecations, mainly see JDK 14 Release Notes, here are a few examples.

Add item

  • New Method to SAX ContentHandler for Handling XML Declaration (JDK-8230814)

Add a method to SAX ContentHandler, as follows

    default void declaration(String version, String encoding, String standalone)
        throws SAXException
    {
        //no op
    }
Copy the code

Remove items

  • Removal of sun.nio.cs.map System Property (JDK-8229960)

Removed the sun.nio.cs.map property

  • Removed Deprecated java.security.acl APIs (JDK-8191138)

Removed the Java. Security. The acl

  • Removal of the Default keytool -keyalg Value (JDK-8214024)

Removed the default keytool -keyalg

Discarded items

  • Thread Suspend/Resume Are Deprecated for Removal (JDK-8231602)

The following method for Thread was deprecated

Thread.suspend()
Thread.resume()
ThreadGroup.suspend()
ThreadGroup.resume()
ThreadGroup.allowThreadSuspension(boolean)
Copy the code

Known issues

  • Text Visibility Issues in macOS Dark Mode (JDK-8228555)

Dark Mode on macOS has Text Visibility Issues

Other matters

  • Thread.countStackFrames Changed to Unconditionally Throw UnsupportedOperationException (JDK-8205132)

Thread. CountStackFrames open to throw an UnsupportedOperationException unconditionally

summary

Java14 has the following features

  • 305:Pattern Matching for instanceof (Preview)
  • 349:JFR Event Streaming
  • 352:Non-Volatile Mapped Byte Buffers
  • 358:Helpful NullPointerExceptions
  • 359:Records (Preview)
  • 361:Switch Expressions (Standard)
  • 363:Remove the Concurrent Mark Sweep (CMS) Garbage Collector
  • 364:ZGC on macOS
  • 366:Deprecate the ParallelScavenge + SerialOld GC Combination
  • 368:Text Blocks (Second Preview)
  • 370:Foreign-Memory Access API (Incubator)

doc

  • JDK 14 Features
  • JDK 14 Release Notes
  • Oracle JDK 14 Release Notes
  • Java SE deprecated-list
  • The Arrival of Java 14!
  • Java Flight Recorder and JFR Event Streaming in Java 14