Main Tutorials

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.

Java 11 developer features.

New HTTP Client APIs java.net.http.*, var in lambda parameters, Java fright recorder (JFR), launch single-file program java ClassName.java, support ChaCha20 cryptography algorithm.

Latest JDK released Java 16
What is new in the latest Java 16.

1. 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

2. 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.

Further Reading

3. 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.

Further Reading

4. 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

Further Reading

5. 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)

Further Reading

6. 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

7. 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);

Further Reading

8. 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

9. 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

10. 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

11. 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);

Further Reading

12. 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!");

    }
}

Further Reading

13. 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

14. 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"});

Further Reading

15. 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 on Linux/64.

  • In Java 14, this ZCG extends support on macOS JEP 364 and Windows JEP 365.
  • This ZGC garbage collector is a product feature in Java 15 JEP 377.

Further Reading

16. 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.

History

  • Java 8 JEP 174 introduced Nashorn, as a replacement for the Rhino Javascript engine.
  • Java 11 JEP 335 deprecated the Nashorn.
  • Java 15 JEP 372 removed the Nashorn JavaScript Engine and jjs tool.

Further Reading

17. 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 Java 14 JEP 367 removed the Pack200 Tools and APIs.

Further Reading

Download Source Code

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

$ cd java-11

References

About Author

author image
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.

Comments

Subscribe
Notify of
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments
Devin Jones
1 year ago

With the new HttpClient in Java 11, how do you handle redirect URIs that contain a ‘state’? I’d like to handle a possible redirect that contains a state value in the URI.