View ToC

Java 17 - Quick Guide



Java 17 - Overview

Java 17 is a major feature release and it has brought many JVM specific changes and language specific changes to JAVA. JAVA 17 was released on September, 2021, just six months after Java 16 release.

Java 17 is a LTS release.

New Features

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

  • JEP 415: Context-Specific Deserialization Filters − Allow apps to use a JVM-wide filter factory to choose a filter for each deserialization operation, allowing them to build context-specific and dynamically selected deserialization filters.

  • JEP 414: Vector API (Second Incubator) − Introduce a platform-agnostic vector API, which was first introduced in JDK 16 and will be reintroduced in JDK 17, for expressing vector computations that reliably compile to optimal vector instructions on supported CPU architectures at runtime, outperforming equivalent scalar computations.
    - The vector API in JDK 17 has been improved for performance and implementation, including enhancements to translate byte vectors to and from boolean arrays.

  • JEP 412: Foreign Function & Memory API (Incubator) − Introduce an API that allows Java programmes to call native libraries and process native data without risking JNI by efficiently executing foreign functions (i.e., code that runs outside of the JVM) and securely accessing foreign memory (i.e. memory not handled by the JVM).
    - The Foreign-Memory Access API and the Foreign Linker API, both incubating APIs, are combined in this JEP proposal. It had previously been the focus of Java 14, 15, and 16

  • JEP 411: Deprecate the Security Manager for Removal − There has been a Security Manager in Java since version 1.0. For many years, however, it has been infrequently used. Security Manager has been deprecated in Java 17 and will be removed in a future version, along with the obsolete Applet API, in order to bring Java forward (JEP 398).

  • JEP 410: Remove the Experimental AOT and JIT Compiler − Because of its limited utility and the enormous work necessary to maintain it, the experimental Java-based ahead-of-time (AOT) and just-in-time (JIT) compiler should be removed.
    - Graal compiler will keep the experimental Java-level JVM compiler interface (JVMCI) so that developers can continue to use externally-built versions of the compiler for JIT compilation.

  • JEP 409: Sealed Classes − Enhance Java programming language with sealed classes and interfaces. Sealed classes and interfaces restrict which other classes or interfaces can extend or implement.

  • JEP 407: Remove RMI Activation − The Activation mechanism for Remote Method Invocation (RMI) will be eliminated, but the remainder of RMI should be kept. The RMI Activation mechanism is no longer in use because it is obsolete. JEP 385 in Java SE 15 recommended that it be deleted because it was deprecated.

  • JEP 406: Pattern Matching for switch (Preview) − Switch pattern matching extends Java's pattern language to allow switch expressions and statements to be checked against a variety of patterns, each with its own action. This allows sophisticated data-oriented queries to be expressed in a simple and secure manner.
    - In JDK 16, the instanceof operator now accepts a type pattern and performs pattern matching. The proposed expansion to the well-known instanceof-and-cast idiom simplifies it.

  • JEP 403: Strongly Encapsulate JDK Internals − Except for crucial internal APIs like sun.misc.Unsafe, strongly encapsulate all internal aspects of the JDK. From JDK 9 through JDK 16, it will no longer be able to relax the rigorous encapsulation of internal sections with a single command-line parameter.

  • JEP 398: Deprecate the Applet API for Removal − Because all online browser makers have either withdrawn or announced plans to eliminate support for Java browser plug-ins, the Applet API is practically obsolete. The Applet API was deprecated in Java 9, but it had not been removed previously.

  • JEP 391: macOS/AArch64 Port − Port the JDK to the new architecture macOS/AArch64 expecting future demand

  • JEP 382: New macOS Rendering Pipeline − The new Apple Metal framework necessitates the development of a new Java 2D rendering pipeline for macOS. Java 2D is still entirely dependant on OpenGL. Although Apple deprecated the OpenGL rendering library in macOS 10.14, the Metal framework now takes its place.

  • JEP 356: Enhanced Pseudo-Random Number Generators − Pseudorandom number generators (PRNGs) get a new interface and implementation, including jumpable PRNGs and a new class of splittable PRNG algorithms (LXM).
    - A focus on numerous areas for development in the field of pseudorandom number generation in Java motivates the strategy. RandomGenerator will have a common API for all current and new PRNGs, as well as four specialised RandomGenerator interfaces.

  • JEP 306: Restore Always-Strict Floating-Point Semantics − Make floating-point operations consistently stringent, rather than having both severe floating-point semantics (strictfp) and drastically varied default floating-point semantics. This will restore the language's and virtual machine's original floating-point semantics, as they were before Java SE 1.2 introduced strict and default floating-point modes.

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

Java 17 - 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 17 - Sealed Classes

Java 15 introduces a sealed classes as preview feature which provides a fine grained control over inheritance. Java 17 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(27, "Robot");
      manager.name = "Robot";
      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

27

Java 17 - 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 17, 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(27, "Robot");
      manager.name = "Robot";
      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

27

Java 17 - 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 17 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 17 - 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 17, 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 17 - 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 17 - 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 17, 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 17 - 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 17 - 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.