What is new in Java 11

Java 11 logo

Java 11 reached General Availability on 25 September 2018, this is a Long Term Support (LTS) version, download Java 11 here or this openJDK archived.

Java 11 features.

JEP 181: Nest-Based Access Control

It supports private access within nest members directly, no more via an auto-generated bridge method access$000. Furthermore, new nested APIs for validation and allowed private reflection access within nest members.

Before Java 11.

.java

public class Alphabet {
    private String name = "I'm Alphabet!";

    public class A {
        public void printName() {
            System.out.println(name);       // access Alphabet's private member!
        }
    }
}

If we compile the above class, it will generate two classes, Alphabet and Alphabet$A, even a nested class is a typical class with a unique name. The JVM access rule will not allow private access within different classes. However, Java allowed private access within nest members, so the Java compiler creates a bridge method access$000 to apply on the JVM access rule.


// After javac Alphabet.java, Java compiler created something similar to this.
public class Alphabet {
  private String name = "I'm Alphabet!";
  String access$000(){
    return name;
  }
}

public class Alphabet$A {
  final Alphabet obj;
  public void printName(){
    System.out.println(obj.access$000());
  }
}

In Java 11, The Java compiler will not generate any bridge method access$000 for private access within nest members. This new JVM access rule, Nest-Based Access Control allowed private access within nest members.

Further Reading
Java 11 – Nest-Based Access Control

JEP 309: Dynamic Class-File Constants

Extends class-file format to support a new constant-pool form, CONSTANT_Dynamic, target language designers and compiler implementors.

JEP 315: Improve Aarch64 Intrinsics

Optimized the existing string and array intrinsics, and implements new intrinsics for Math.sin(), Math.cos() and Match.log() on Arm64 or Aarch64 processors. it means better performance.

P.S An intrinsic is used to leverage CPU architecture-specific assembly code to improve the performance.

JEP 318: Epsilon: A No-Op Garbage Collector (Experimental)

A new No-Op (no operations) Garbage Collector, it allocates memory but will not collect any garbage (memory allocation), once the Java heap is exhausted, the JVM will shut down.

A few use cases:

  • Performance testing
  • VM interface testing
  • Short-lived jobs

This GC is an experimental feature; we need to use the following options to enable the new Epsilon GC.


-XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC

JEP 320: Remove the Java EE and CORBA Modules

Java 9 deprecated the following Java EE and CORBA modules and now removed in Java 11. If you want to migrate to Java 11, make sure your project didn’t use any of the following packages or tools.

Removed packages:

  • java.xml.ws (JAX-WS)
  • java.xml.bind (JAXB)
  • java.activation (JAF)
  • java.xml.ws.annotation (Common Annotations)
  • java.corba (CORBA)
  • java.transaction (JTA)
  • java.se.ee (Aggregator module for the six modules above)

Removed Tools:

  • wsgen and wsimport (from jdk.xml.ws)
  • schemagen and xjc (from jdk.xml.bind)
  • idlj, orbd, servertool, and tnamesrv (from java.corba)

JEP 321: HTTP Client (Standard)

This HTTP Client API, in the java.net.http package was introduced in Java 9, updated in Java 10, now a standard feature in Java 11.

A Java 11 HttpClient to send a simple GET request.


    HttpClient httpClient = HttpClient.newBuilder()
            .version(HttpClient.Version.HTTP_1_1)
            .connectTimeout(Duration.ofSeconds(10))
            .build();

    HttpRequest request = HttpRequest.newBuilder()
            .GET()
            .uri(URI.create("https://httpbin.org/get"))
            .setHeader("User-Agent", "Java 11 HttpClient Bot")
            .build();

    HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

    HttpHeaders headers = response.headers();
    headers.map().forEach((k, v) -> System.out.println(k + ":" + v));

    System.out.println(response.statusCode());
    System.out.println(response.body());

Further Reading
Java 11 HttpClient Examples

JEP 323: Local-Variable Syntax for Lambda Parameters

This JEP adds support for the var keyword in lambda parameters.


  List<String> list = Arrays.asList("a", "b", "c");
  String result = list.stream()
          .map((var x) -> x.toUpperCase())
          .collect(Collectors.joining(","));
  System.out.println(result2);

However, the lambda can make type inference; the above example is equivalent to this:


  List<String> list = Arrays.asList("a", "b", "c");
  String result = list.stream()
          .map(x -> x.toUpperCase())
          .collect(Collectors.joining(","));

then, why this JEP adds var in lambda parameters? The benefit is now we can add annotations to the lambda parameters, see this example:


import org.jetbrains.annotations.NotNull;

  List<String> list = Arrays.asList("a", "b", "c", null);
  String result = list.stream()
          .map((@NotNull var x) -> x.toUpperCase())
          .collect(Collectors.joining(","));
  System.out.println(result3);

JEP 324: Key Agreement with Curve25519 and Curve448

Java Cryptography related item. It replaced the existing elliptic curve Diffie-Hellman (ECDH) scheme with Curve25519 and Curve448 algorithms, a key agreement scheme defined in RFC 7748.

A simple KeyPairGenerator example using the Curve25519 algorithm to generate a key pair.

GenerateKeyPairs.java

package com.mkyong.java11.jep324;

import java.nio.charset.StandardCharsets;
import java.security.*;
import java.security.spec.NamedParameterSpec;

public class GenerateKeyPairs {

    public static void main(String[] args) throws NoSuchAlgorithmException,
        InvalidAlgorithmParameterException {

        KeyPairGenerator kpg = KeyPairGenerator.getInstance("XDH");
        NamedParameterSpec paramSpec = new NamedParameterSpec("X25519");
        kpg.initialize(paramSpec); // equivalent to kpg.initialize(255)
        // alternatively: kpg = KeyPairGenerator.getInstance("X25519")
        KeyPair kp = kpg.generateKeyPair();

        System.out.println("--- Public Key ---");
        PublicKey publicKey = kp.getPublic();

        System.out.println(publicKey.getAlgorithm());   // XDH
        System.out.println(publicKey.getFormat());      // X.509

        // save this public key
        byte[] pubKey = publicKey.getEncoded();

        System.out.println("---");

        System.out.println("--- Private Key ---");
        PrivateKey privateKey = kp.getPrivate();

        System.out.println(privateKey.getAlgorithm());  // XDH
        System.out.println(privateKey.getFormat());     // PKCS#8

        // save this private key
        byte[] priKey = privateKey.getEncoded();
    }
}

Further Reading
Refer to the JEP 324 and Oracle – Java Security Standard Algorithm Names for more examples.

JEP 327: Unicode 10

It means more code points, more emoji icons 🙂 The below example prints a Unicode code point.

PrintUnicode.java

package com.mkyong.java11;

public class PrintUnicode {

    public static void main(String[] args) {
        String codepoint = "U+1F92A";   // crazy face
        System.out.println(convertCodePoints(codepoint));
    }

    // Java, UTF-16
    // Convert code point to unicode
    static char[] convertCodePoints(String codePoint) {
        Integer i = Integer.valueOf(codePoint.substring(2), 16);
        char[] chars = Character.toChars(i);
        return chars;

    }

}

Further Reading.

JEP 328: Flight Recorder

Java Flight Recorder (JFR) was a commercial product in Oracle JDK, now it is open source in OpenJDK 11. This JFR is a profiling tool that used to diagnose a running Java application. The below command starts a 60 seconds JFR recording on a Java application, dumps the recorded data into a ‘.jfr’ file.

Termianl

$ java -XX:StartFlightRecording=duration=60s,settings=profile,filename=app.jfr MyHelloWorldApp

So what to do with the .jfr file? We can use Java Mission Control (JMC) to analyze and visualize the .jfr file.

Further Reading
Java Flight Recorder

JEP 329: ChaCha20 and Poly1305 Cryptographic Algorithms

ChaCha20 is a high-speed stream cipher, an encryption and decryption algorithm. ChaCha20-Poly1305 means ChaCha20 running in AEAD mode with the Poly1305 authenticator, encryption and authentication together, both are defined in RFC 7539. This JEP update of ChaCha20 cryptographic algorithms is a replacement for the insecure RC4 stream cipher.

The inputs to ChaCha20 are:

  • A 256-bit secret key (32 bytes)
  • A 96-bit nonce (12 bytes)
  • A 32-bit initial count (4 bytes)

    Cipher cipher = Cipher.getInstance("ChaCha20");

    ChaCha20ParameterSpec param = new ChaCha20ParameterSpec(nonce, counter);

    cipher.init(Cipher.ENCRYPT_MODE, key, param);

    byte[] encryptedText = cipher.doFinal(pText);

Please refer to this Java 11 – ChaCha20 Stream Cipher examples

The inputs to ChaCha20-Poly1305 are:

  • A 256-bit secret key (32 bytes)
  • A 96-bit nonce (12 bytes)

   Cipher cipher = Cipher.getInstance("ChaCha20-Poly1305");

   // IV, initialization value with nonce
   IvParameterSpec iv = new IvParameterSpec(nonce);

   cipher.init(Cipher.ENCRYPT_MODE, key, iv);

   byte[] encryptedText = cipher.doFinal(pText);

Please refer to this Java 11 – ChaCha20-Poly1305 encryption examples

JEP 330: Launch Single-File Source-Code Programs

This Single-File Source-Code Program means the entire Java program in a single source code .java file. This JEP is a friendly feature in the early stage of learning Java, but not much benefit in Java development, we all use IDE.

Review a single file source code.

HelloJava.java

public class HelloJava {

    public static void main(String[] args) {

        System.out.println("Hello World!");

    }
}

Before Java 11.

Termianl

$ javac HelloJava.java

$ java HelloJava

Hello World!

Now Java 11.

Termianl

$ java HelloJava.java

Hello World!

Shebang #!
Now, the single Java program can run as a script using Linux Shebang.

run.sh

#!/opt/java/openjdk/bin/java --source 11
public class SheBang {

    public static void main(String[] args) {

        System.out.println("Hello World!");

    }
}

Refer to this Java 11 shebang example in Docker

JEP 331: Low-Overhead Heap Profiling

Java Virtual Machine Tool Interface (JVMTI) was introduced in J2SE 5, JDK 5 (Tiger), it provides APIs for profiling or monitoring tools to access the JVM state. This JEP added new low overhead heap profiling API into the JVMIT.

Further Reading
Oracle – JVMTM Tool Interface

JEP 332: Transport Layer Security (TLS) 1.3

Java 11 supports RFC 8446 Transport Layer Security (TLS) 1.3 protocol. However, not all TLS 1.3 feature is implemented, refer to this JEP 332 for detail.

Java Secure Socket Extension (JSSE) + TLS 1.3 example.


import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

SSLSocketFactory factory =
        (SSLSocketFactory) SSLSocketFactory.getDefault();
socket =
        (SSLSocket) factory.createSocket("google.com", 443);

socket.setEnabledProtocols(new String[]{"TLSv1.3"});
socket.setEnabledCipherSuites(new String[]{"TLS_AES_128_GCM_SHA256"});

Refer to this Java SSLSocket TLS 1.3 example

JEP 333: ZGC: A Scalable Low-Latency Garbage Collector (Experimental)

The Z Garbage Collector (ZGC) is an experimental garbage collector; it has low pause times not exceed 10ms. This ZCG support only in Linux/64.

Futher Reading

P.S In Java 14, this ZCG extends support on macOS JEP 364 and Windows JEP 365.

JEP 335: Deprecate the Nashorn JavaScript Engine

The Nashorn JavaScript script engine and the jjs tool are deprecated, and it will probably remove in the future release.

P.S Nashorn was introduced in Java 8 JEP 174, as a replacement for the Rhino Javascript engine.

JEP 336: Deprecate the Pack200 Tools and API

This JEP deprecates the pack200 and unpack200 tools, and the Pack200 API in java.util.jar package, and it will probably remove in the future release.

P.S The Pack200 Tools and API are removed in Java 14 JEP 367.

Download Source Code

$ git clone https://github.com/mkyong/core-java

$ cd java-11

References

author image

mkyong

Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities. Read all published posts by

Comments

avatar