What’s new in Java 9?

Java, the highly accessible programming language has been a no-brainer for developers across the globe. Ever since it’s inception in 1995, the language has seen wide usage across various industries.

Today, you will find Java in your phones. Powering Android OS and the myriad range of apps that Android offers. It is used for developing games like Minecraft which has a huge player-base. It also finds use in business applications like reading credit card information at shop tills and feeding the information between the systems and the banks.

After a gap of 3 years, Java rolled out its new edition – Java SE 9.  With several key architectural changes and add-on features, Java SE 9 offers a powerful solution that developers had been yearning for.

Java 7 added try-with-resource in 2011, offering better resource management functionality.

Java 8 added lambda expressions, a good move but slightly flawed under OOP paradigm.

Now Java 9 allows programmers to have private methods. Private static methods! YES, you read that right!

Java SE 8 offered many structural changes that were received with mixed emotions by developers. Majorly, these are the shortcomings of Java SE 8 that Java SE 9 has tried to overcome:

  • The JDK was not navigable for small computing devices
  • There was no overall improvement in application performance.
  • There was no overall security and maintenance of JDK
  • Java developers faced difficulty to build and uphold the code libraries and larger applications

So, let’s look at the key changes and enhancements that Java 9 offers over its predecessors.

Process API updates in Java 9

Traditionally, Java’s API has been primitive in nature. With support to launch new processes, redirect output and error streams. In Java 9, the updates to the Process API enable:

  • Getting the PID of the current and any other JVM process
  • Managing subprocesses
  • Managing subprocesses
  • Get information such as PID, name, and resource usage of the processes running in the system.

This is a sample code, which prints the current PID as well as the current process information:

 public class NewFeatures{

 

      public static void main(String [] args)

   {

 

            ProcessHandle currentProcess = ProcessHandle.current();

 

            System.out.println(“PID:”+ currentProcess.getPid());

 

            ProcessHandle.Info currentProcessInfo = currentProcess.info();

 

      System.out.println(“Info:” + currentProcessInfo);

         }

HTTP/2 client in Java 9

This feature is expected to be reformed in the subsequent releases or may even be removed completely. 

Earlier developers would rely on third-party libraries, such as Apache HTTP, Jersey, and so on. Java’s HTTP API predates the HTTP/1.1 specification and is synchronous and hard to maintain. These limitations called for the need to add a new API. The new HTTP client API provides the following:

  • A simple and concise API to deal with most HTTP requests
  • Support for HTTP/2 specification
  • Better performance
  • Better security
  • A few more enhancements

Here is a code snippet to make an HTTP GET request using the new APIs. This is the module as defined in the file module-info.java:

module newfeatures{

       requires jdk.incubator.httpclient;

    }

 

The following code uses HTTP Client API. This is a part of jdk.incubator.httpclient module:

import jdk.incubator.http.*;

import java.net.URI;

public class Http2Feature{

     public static void main(String[] args) throws Exception{

       HttpClient client = HttpClient.newBuilder().build();

       HttpRequest request = HttpRequest

.newBuilder(new URI(http://httpbin.org/get;))

.GET()

.version(HttpClient.Version.HTTP_1_1)

.build();

HttpResponse.String response = client.send(request,

HttpResponse.BodyHandler.asString());

System.out.println(“Status code:” + response.statusCode());</pre>

<pre>System.out.println(“Response Body:” + response.body());

                       }

          }

}

More Concurrency Updates feature in Java 9

With Java 9, a new class called – java.util.concurrent.Flow has been introduced, which supports the implementation of a publish-subscribe framework. This framework enables developers to build components. These components can asynchronously consume a live stream of data by setting up publishers that produce the data and subscribers that consume the data. These are the new interfaces:

  • java.util.concurrent.Flow.Publisher
  • java.util.concurrent.Flow.Subscriber
  • java.util.concurrent.Flow.Subscription
  • java.util.concurrent.Flow.Processor (which acts as both Publisher and Subscriber).

Java Shell Scripting (Read-Eval-Print-Loop) in Java 9

The goal of Project Kulla was to investigate the addition of the REPL (Read-Eval-Print-Loop) tool for Java 9. This release of Java features a special command line tool called JShell. The goal here is to popularize and maximize usage of REPL. So, what does that mean? Now, you do not need to wrap a few lines of code in a separate method to run them. Efficient? I say YES.

For instance, in Scala, a simple Hello World program is written as scala>println(“Hello World”);

Let’s run the JShell command, as shown in the following image:

Project Jigsaw in Java 9

The trump card of the new features in Java 9 is the all new module system. Creating complex systems often involves high level, complex codes which results in ambiguity. With code complexity, two fundamental problems are faced: Encapsulation of the code is difficult, and there is no notion of explicit dependencies between different JAR files of a system. Every public class can be accessed by any other public class on the class path. This leads to unnecessary usage of classes that weren’t meant to be public API. Furthermore, the class path itself is problematic: How do you know whether all the required JARs are there, and what about duplicate entries? The module system resolves both issues.

This is where the robust nature of Java 9 is seen. Modular JAR files contain an additional module descriptor. In this module descriptor, `requires` statements are used to express dependencies on other modules. Additionally, `exports` statements control which packages are accessible to different modules. By default, all non-exported packages are encapsulated in the module.

There are various JEPs, which are part of this project, as follows:

  • JEP 200 – modular JDK: This applies the Java platform module system to modularize the JDK that can be combined at compile time, build time, or runtime.
  • JEP 201 – modular source code: This is the source code that creates the modules. It also allows the build tools to compile these modules.
  • JEP 220 – modular runtime images: This JEP improves performance, security, and maintainability by restructuring the JDK and JRE runtime images to accommodate modules
  • JEP 282: jlink, the Java linker: This allows packaging modules and their dependencies into smaller run times. 

Multi-release JAR files

To leverage the new features of the Java platform on newer versions, the library developers must release a newer version of their library. Soon, there will be multiple versions of the library being maintained by the developers, which can be catastrophic. To overcome this limitation, Java 9 features multi-release of JAR files allowing developers to build JAR files with different versions of class files for different Java versions. Take a look at this example. 

Here is an illustration of the current JAR files:

jar root 

    – A.class

    – B.class 

    – C.class

Here are how multi-release JAR files look:

jar root 

 

     – A.class 

     – B.class 

     – C.class 

     – META-INF  

      – versions

             – 9  

                – A.class  

            – 10 

                – B.class

In the preceding illustration, the JAR files support class files for two Java versions–9 and 10.

So, when the earlier JAR is executed on Java 9, the A.class under the versions – 9 folders are picked up for execution.

The earlier versions of Java that doesn’t support multi-release JAR files, the classes under the versions directory are never used. So, if you run the multi-release JAR file on Java 8, it’s as good as running a simple JAR file.

In my opinion, things are starting to change with Java. And this is a growing trend. Does it mean that popularity of Java and it’s uses will be affected? Not at all. Java has been and still is an incredibly powerful and robust programming language in the tech industry today. Start learning Java and watch it make a difference in your career. Good luck!

Author’s note:

Sumit is a tech enthusiast with an engineering degree. He is an avid gamer and an e-sports fanatic. Curious by birth, you can find him sharing his opinions on topics ranging from music and sports to trending technologies such as DevOps, Big Data, and Python. He works in the Digital Marketing team at Edureka.