View ToC

Java 16 - Quick Guide



Java 16 - Overview

Java 16 is a major feature release and it has brought many JVM specific changes and language specific changes to JAVA. It followed the Java release cadence introduced Java 10 onwards and it was released on Mar 2021, just six months after Java 15 release.

Java 16 is a non-LTS release.

New Features

Following are the major new features which are introduced in Java 16.

  • JEP 338 - Vector API (Incubator) − New Vector APIs introduced allowing developers to perform the vector operations explicitly.

  • JEP 347 - Enable C++14 Language Features − C++ 14 features can be used in c++ source code with the JDK 16.

  • JEP 357, JEP 369 - Migrate from Mercurial to Git/GitHub − OpenJDK source code is moved from mercurial to Git/GitHub

  • JEP 376 - ZGC - Concurrent Thread-Stack Processing − Z Garbage Collector improved by moving its thread-stack processing from safepoints to concurrent phase.

  • JEP 380 - Unix-Domain Socket Channels − SocketChannel and ServerSocketChannel now supports Unix Domain sockets.

  • JEP 386 - Alpine Linux Port − Now JDK is available for Alpine Linux and other Linux distributions which use musl implementation.

  • JEP 387 - Elastic Metaspace − Metaspace memory management is improved by returning unused HotSpot class-metadata or metaspace memory to the operating system quickly, reduces the metaspace footprint, and simplify the metaspace code.

  • JEP 388 - Windows/AArch64 Port − Now JDK can run on AArch64, on ARM hardware server or ARM based laptops.

  • JEP 389 - Foreign Linker API (Incubator) − Java code can be called by C/C++ or vice versa using new API replacing the JNI.

  • JEP 390 - Warnings for Value-Based Classes − Warnings are raised in case of value-based classes are synchronised using synchronize.

  • JEP 392 - Packaging Tool − jpackage is now a standard instead of incubator feature.

  • JEP 393 - Foreign-Memory Access API (Third Incubator) − Minor enhancements to Foreign Memory Access API.

  • JEP 394 - Pattern Matching for instanceof − Pattern matching for instanceOf is now a standard feature.

  • JEP 395 - Records − records are now a standard feature.

  • JEP 396 - Strongly Encapsulate JDK Internals by Default − default mode of --illegal-access option is now deny. Earlier it was permit.

  • JEP 397 - Sealed Classes (Second Preview) − Minor enhancements to sealed classes.

Java 16 enhanced numerous APIs with new methods and options. We'll see these changes in next chapters.

Java 16 - Environment Setup

Live Demo Option Online

We have set up the Java Programming environment online, so that you can compile and execute all the available examples online. It gives you confidence in what you are reading and enables you to verify the programs with different options. Feel free to modify any example and execute it online.

Try the following example using Live Demo option available at the top right corner of the below sample code box −

Example

public class MyFirstJavaProgram {
   public static void main(String []args) {
      System.out.println("Hello World");
   }
}

Output

Hello World

For most of the examples given in this tutorial, you will find a Live Demo option in our website code sections at the top right corner that will take you to the online compiler. So just make use of it and enjoy your learning.

Local Environment Setup

If you want to set up your own environment for Java programming language, then this section guides you through the whole process.Please follow the steps given below to set up your Java environment.

Java SE is available for download for free.To download click here, please download a version compatible with your operating system.

Follow the instructions to download Java, and run the .exe to install Java on your machine. Once you have installed Java on your machine, you would need to set environment variables to point to correct installation directories.

Setting Up the Path for Windows 2000/XP

Assuming you have installed Java in c:\Program Files\java\jdk directory −

  • Right-click on 'My Computer' and select 'Properties'.

  • Click on the 'Environment variables' button under the 'Advanced' tab.

  • Now, edit the 'Path' variable and add the path to the Java executable directory at the end of it. For example, if the path is currently set to C:\Windows\System32, then edit it the following way

    C:\Windows\System32;c:\Program Files\java\jdk\bin.

Setting Up the Path for Windows 95/98/ME

Assuming you have installed Java in c:\Program Files\java\jdk directory −

  • Edit the 'C:\autoexec.bat' file and add the following line at the end −

    SET PATH=%PATH%;C:\Program Files\java\jdk\bin

Setting Up the Path for Linux, UNIX, Solaris, FreeBSD

Environment variable PATH should be set to point to where the Java binaries have been installed. Refer to your shell documentation if you have trouble doing this.

For example, if you use bash as your shell, then you would add the following line at the end of your .bashrc

  • export PATH=/path/to/java:$PATH'

Popular Java Editors

To write Java programs, you need a text editor. There are even more sophisticated IDEs available in the market. The most popular ones are briefly described below −

  • Notepad − On Windows machine, you can use any simple text editor like Notepad (recommended for this tutorial) or WordPad. Notepad++ is also a free text editor which enhanced facilities.

  • Netbeans − It is a Java IDE that is open-source and free which can be downloaded from www.netbeans.org/index.html.

  • Eclipse − It is also a Java IDE developed by the Eclipse open-source community and can be downloaded from www.eclipse.org/.

IDE or Integrated Development Environment, provides all common tools and facilities to aid in programming, such as source code editor, build tools and debuggers etc.

Java 16 - Sealed Classes

Java 15 introduces a sealed classes as preview feature which provides a fine grained control over inheritance. Java 16 provides some minor enhancements and keep this feature as Preview. Following are salient points to consider for a sealed class −

  • Sealed class is declared using sealed keyword.

  • Sealed classes allow to declare which class can be a subtype using permits keyword.

  • A class extending sealed class must be declared as either sealed, non-sealed or final.

  • Sealed classes helps in creating a finite and determinable hiearchy of classes in inheritance.

Example

Consider the following example −

ApiTester.java

public class APITester {
   public static void main(String[] args) {
      Person manager = new Manager(23, "Robert");
      manager.name = "Robert";
      System.out.println(getId(manager));
   }
   public static int getId(Person person) {
      if (person instanceof Employee) {
         return ((Employee) person).getEmployeeId();
      } 
      else if (person instanceof Manager) {
         return ((Manager) person).getManagerId();
      }
      return -1;
   }
}
abstract sealed class Person permits Employee, Manager {
   String name;
   String getName() {
      return name;
   }
}
final class Employee extends Person {
   String name;
   int id;
   Employee(int id, String name){
      this.id = id;
      this.name = name;
   }
   int getEmployeeId() {
      return id;
   }
}
non-sealed class Manager extends Person {
   int id;
   Manager(int id, String name){
      this.id = id;
      this.name = name;
   }
   int getManagerId() {
      return id;
   }
}

Compile and Run the program

$javac -Xlint:preview --enable-preview -source 16 APITester.java
$java --enable-preview APITester

Output

23

Java 16 - Pattern Matching for instanceof

Java 14 introduces instanceof operator to have type test pattern as is a preview feature. Type test pattern has a predicate to specify a type with a single binding variable. It continues to be a preview feature in Java 15 as well. With Java 16, this feature is now a part of standard delivery.

Syntax

if (person instanceof Employee e) {
   return e.getEmployeeId();
}

Example

Consider the following example:

ApiTester.java

public class APITester {
   public static void main(String[] args) {
      Person manager = new Manager(23, "Robert");
      manager.name = "Robert";
      System.out.println(getId(manager));
   }
   public static int getId(Person person) {
      if (person instanceof Employee e) {
         return e.getEmployeeId();
      } 
      else if (person instanceof Manager m) {
         return m.getManagerId();
      }
      return -1;
   }
}
abstract class Person {
   String name;
   String getName() {
      return name;
   }
}
final class Employee extends Person {
   String name;
   int id;
   Employee(int id, String name){
      this.id = id;
      this.name = name;
   }
   int getEmployeeId() {
      return id;
   }
}
final class Manager extends Person {
   int id;
   Manager(int id, String name){
      this.id = id;
      this.name = name;
   }
   int getManagerId() {
      return id;
   }
}

Compile and Run the program

$javac APITester.java
$java APITester

Output

23

Java 16 - Warning for Value-Based Classes

Some classes, such as java.util.Optional and java.time.LocalDateTime, are value-based. Such Instances of a value-based class are final and immutable. Such classes have annotation @jdk.internal.ValueBased and Java 16 now generates compile time warnings in case such classes are synchronized using synchronized keyword. Wrapper classes are value based. For example, Double class is a value based.

Example

package java.lang;
@jdk.internal.ValueBased
public final class Double extends Number
   implements Comparable<Double>, Constable, ConstantDesc {
   //...
}

Consider the following example:

ApiTester.java

Example

public class APITester {
   public static void main(String[] args) {
      Double d = 10.0;
      synchronized (d) {
         System.out.println(d);			
      } 
   }
}

Compile and Run the program

$javac APITester.java

Output

APITester.java:4: warning: [synchronization] attempt to synchronize on an instance of a value-based class
   synchronized (d) {
   ^
1 warning

Java 16 - Record

Java 14 introduces a new class type record as preview feature to facilitate creation of immutable data objects. Java 15 enhances record type further. With Java 16, record is now a standard feature of JDK.

Consider the following example −

ApiTester.java

Example

public class APITester {
   public static void main(String[] args) {
      StudentRecord student = new StudentRecord (1, "Julie", "Red", "VI", 12);
      System.out.println(student.id());
      System.out.println(student.name());
      System.out.println(student);
   } 
}
record StudentRecord(int id, 
   String name, 
   String section, 
   String className,
   int age){}

Compile and Run the program

$javac APITester.java
$java APITester

Output

1
Julie
StudentRecord[id=1, name=Julie, section=Red, className=VI, age=12]

Java 16 - Packaging Tools

Java 14 introduces a new packaging tool, jpackage based on javapackager. javapackager was introduced in Java 8 and was part of JavaFX kit. As JavaFX is split from Java from 11 version, this packaging tool is no more available in standard offering.

This new tool is developed to provide native installer for an operating system. For example, an msi/exe for windows, pkg/dmg for MacOS, deb/rpm for Linux and so on. Without this tool, developer generally share a jar file which a user has to run within own JVM.

Developer can use jlink to compress the required JDK modules to minimum modules and use the jpackage to create a lightweight image.

Consider the following example −

APITester.java

Example

public class APITester {
   public static void main(String[] args) {
      System.out.println("Welcome to TutorialsPoint.");
   }   
}

Compile and Run the program

$javac APITester.java
$jar cf APITester.jar APITester.class

Output

For windows executable, you need to download WiX Toolset v3.11.2(wix311-binaries.zip) and add the toolkit to your path.

Once jar is created and path is set, put jar in a folder called lib and run the following command to create a windows MSI installer.

$jpackage --input lib --name APITester --main-jar APITester.jar --main-class APITester --type msi

Java 16 - Garbage Collectors

Java 15 has made the ZGC, Z Garbage Collector a standard feature. It was an experimental feature till Java 15. It is low latency, highly scalable garbage collector.

ZGC was introduced in Java 11 as an experimental feature as developer community felt it to be too large to be released early.

ZGC is highly performant and works efficiently even in case of massive data applications e.g. machine learning applications. It ensures that there is no long pause while processing the data due to garbage collection. It supports Linux, Windows and MacOS.

With Java 16, ZGC Thread-Stack processing is moved from Safepoints to Concurrent Phase and improved its efficiency to great extent. Following are the enhancements made.

  • Thread-stack processing moved from ZGC safepoints.

  • Stack processing is made lazy, cooperative, concurrent, and incremental.

  • All other per-thread root processing are removed from ZGC safepoints.

  • HotSpot subsystems can lazily process stacks.

Java 16 - Other Enhancements

JEP 338 − Vector API (Incubator)

JIT Compiler optimizes the arithmetic algorithms, by transforming some scalar operations (one item at a time) into vector operations (multiple items at a time) automatically. But developers had no control over this process. Even not all scalar operations can be converted into vector operations. With this JEP, a new VECTOR API is introduced to allow developers to perform Vector operations explicitly.

It is an incubator module, jdk.incubator.vector, to express vector computations to reliably compile at runtime to optimal vector hardware instructions.

JEP 347 − Enable C++14 Language Features

Till JDK 15, JDK supports C++98/03 language standards. With JEP 347, now Java formally allow C++ source code changes within the JDK to use C++14 language features, and to provide specific guidance about which of those features may be used in HotSpot code.

JEP 357/369 − Migrate from Mercurial to GitHub

With JEP 357/369, OpenJDK Source code is moved from Mercurial to Git/GitHub. Following are the primary factors for this movement.

  • Large File size of version control system metadata (Mercurial)

  • Available tooling

  • Available hosting

JEP 380 − Unix-Domain Socket Channels

The Unix-domain sockets are for inter-process communication (IPC) on the same host, to exchange data between processes. These sockets are similar to TCP/IP sockets except being addressed by filesystem pathnames rather than the Internet Protocol (IP) addresses and port numbers. Most Unix platforms, Windows 10 and Windows Server 2019, supports the Unix-domain sockets. JEP 380 added Unix-domain socket support to SocketChannel and ServerSocketChannel.

Java 16 - Deprecation and Removals

Deprecation

  • ThreadGroup methods like stop, destroy, isDestroyed, setDaemon and isDaemon methods are deprecated and will be removed in future release. These API/mechanism to destroy a threadgroup is flawed and such method which supports explicitly or automatically destroying a thread group are terminally deprecated.

  • Signal Chaining APIs like sigset, signal are obsolete and their use is deprecated. sigaction is cross-platform and is supported API for multi-threaded processes.

  • java.security.cert APIs representing DNs as Principal or String objects are deprecated.

  • elliptic curves which are either obsolete or not implemented using modern formulas and techniques of SunEC provider are removed.

Removals

  • The non-public class java.awt.PeerFixer is removed. Its purpose was to provide deserialization support of ScrollPane objects created prior JDK 1.1.1.

  • jaotc, an experimental Java Ahead-of-Time compilation tool is removed. Experimental Java-based JIT compiler, Graal, is also removed.

  • root certificates with weak 1024-bit RSA public keys have been removed from the cacerts keystore.