Java 9 features and improvements

In this article, we will discuss newly added Java 9 features. Oracle has released Open JDK 9 with the several new features and improvements on July 27, 2017. Java 9 brings outstanding improvements and new enhancements to the previous Java versions that will ensure that your coding methods and habits are completely altered and improved in a way that benefits facilitate you. The greatest difference brought about by Java 9 is the modularization of Java. It is one of the major changes brought in Java programme after the onset of Lambdas in Java 8. Here, we will list down the changes that will constitute the Java 9 release.

java 9 features
Newly Added Java 9 features and Improvements

Open JDK 9 was released with several features as the following:

Let’s see these Java 9 features in details:

Java platform module system – Jigsaw Project

Java Platform Module System is considered as the highlight of the latest Java 9 release. It is the most significant feature in the release of Java 9. It’s an application made using a latest modular programming and is visible as a collection of modules interacting with each other respective of the boundaries specified and the dependencies between those modules.

The Java platform module system provides support for various writing modular applications. It also modularizes the Java 9 source code as the following:

  • Modular JDK
  • Modular Java Source Code
  • Modular Run-time Images
  • Encapsulate Java Internal APIs
  • Java Platform Module System

Before Java SE 9 versions, we are using Monolithic Jars to develop Java-Based applications. This architecture has a lot of limitations and drawbacks. To avoid all these shortcomings, Java SE 9 is coming with Module System.

Simple Module Example

Let’s see how to write java modular programming-

In Java modular programming, a module is just a jar file and it has a class module-info.class at the root of a module.
To use this module, you have to add this module file into modulepath instead of the classpath.

A module is typically just a jar file that has a module-info.class file at the root.

Let’s see the module-info.java file looks like this:

module book {
    requires com.dineshonjava.java9.modules.chapters;
    exports com.dineshonjava.java9.modules.book.codes
}
  
module student{
    requires book;
}

Our module book requires module chapters to run and exports a package for codes.

Interface Private Method

The previously released Java 8 enabled coders to use default methods in the interfaces. It has been one of the most prominent and important milestones the Java 8 release had covered. There wasn’t much room left for improvement after the release of that specific Java 8 feature. A non-private method was one of the aspects of default methods feature that needed further development. Hence, from after the release of Java 9, you can make use of private methods in interfaces.

The advantage of the private methods is that they’ll improvise program’s re-usability within interfaces. For instance, if two defaults methods are required to share a snippet, a private interface method will enable the operation, but it would also protect that particular private method from the implementing classes.

We have to follow four rules to use private methods within interfaces:

  • The private interface method should not be abstract.
  • The method can only be used inside of an interface.
  • While the private static method may be written within another interface method.
  • Private non-static methods will not be used within other private static methods.

Interfaces in the upcoming JVM version can have private methods, which can be used to split lengthy default methods:

public interface MyInterface {

    void normalInterfaceMethod();

    default void interfaceMethodWithDefault() {  init(); }

    default void anotherDefaultMethod() { init(); }

    // This method is not part of the public API exposed by MyInterface
    private void init() { System.out.println("Initializing"); }
}

Java 9 REPL (JShell)

JShell is a command line and a tool that interacts with its users and has come with the new Java 9 release. The purpose of JShell is the evaluation of declarations, statements, and expressions of JavaScript. JShell gives its users the permission to compile Java code snippets and obtain fast results without having to create a solution. JShell is a lot like the command window present in the Linux Operating System. The only difference is the JShell is exclusively Java specific. JShell has a lot of capabilities besides executing normal code snippets. For example, JShell can be used for the execution of the following tasks:

  • JShell can launch an inbuilt code editor in an entirely new window. The code editor could be any desired, too.
  • It can execute the code while Save operation happens in these editors.
  • JShell can also load previously written classes within the file system.

Platform and JVM Logging

Java 9 has improvised logging in various different platform classes and JVM components via the latest logging API. It allows the user to specify a logging framework of their choice. There are a few things you should understand regarding this API:

  • The API is for classes in Java, and not for application classes.
  • For a user’s application code, will just be using other logging APIs.
  • The API cannot give you the permission to configure the logger programmatically.

The API consists of the following three parts:

  • Java.lang.System.LoggerFinder is a service interface that belongs to an abstract static class.
  • java.lang.System.Logger is an interface that gives the logging API.
  • To return logger instance, overloaded method getLogger() in the java.lang.System class.

The new Java 9 also comes with a new option, -Xlog. It gives you permission to various messages logged within classes of the JVM. The practiced –Xlog syntax is given below:

-Xlog[:][:[][:[][:]]]

All options are optional. If a preceding part in -Xlog is missing, you must use a colon for that part.

Process API Updates

Before Java 5, the one method to spawn new processes was to utilize the Runtime.getRuntime().exec() method. After that with the release of Java 5, ProcessBuilder API was introduced to the users. ProcessBuilder brought about a more advanced way of spawning latest methods. With the release of Java 9, the user will get to experience a new way of gathering information.

To find info of any process, you can now use java.lang.ProcessHandle.Info interface and collect important info. This interface is purposeful in getting plenty of useful information. Following are a few examples:

  • It tells us about the command that is used to initiate the process
  • Notifies us of the command’s arguments
  • Notifies the user of the value of time instant when the procedure was initiated
  • And also displays the overall duration by the process and the user who created it.

Two new interfaces in Process API:

  • java.lang.ProcessHandle
  • java.lang.ProcessHandle.Info

Process API example

 ProcessHandle currentProcess = ProcessHandle.current();
 System.out.println("Current Process Id: = " + currentProcess.getPid());

Collection API Updates

Since Jaav 9, you can use factory methods for immutable List, Set, Map and Map.Entry. Let’s see the following example:

import java.util.List;
import java.util.Set;
import java.util.Map;
  
public class ImmutableCollections
{
    public static void main(String[] args)
    {
        List<String> namesList = List.of("Dinesh", "Anamika", "Arnav", "Rushika");
 
        Set<String> namesSet = Set.of("Dinesh", "Anamika", "Arnav", "Rushika");
 
        Map<String, String> namesMap = Map.ofEntries(
                                    Map.entry("1", "Dinesh"),
                                    Map.entry("2", "Anamika"),
                                    Map.entry("3", "Arnav")),
                                    Map.entry("4", "Rushika"));
    }
}

Stream API Improvements

Java 9 has java.util.Stream interface. The Stream is an interface, all those new implemented methods are default methods. Two of them are very important: dropWhile and takeWhile methods. These methods are very similar to the Scala Language or any Functions programming language’s methods.

java.util.Optional.stream() gives us an easy way to you use the power of Streams on Optional elements:

Stream.of(1,2,3,4,5,6,7,8,9,10).takeWhile(i -> i < 5 )
                 .forEach(System.out::println);

Reactive Streams

It is one of the very interesting new added features into Java 9 and it is very popular nowadays. Reactive programming has become very popular in developing applications to get some beautiful benefits. Languages such as Scala, Play, Akka etc. have already integrated Reactive Streams and getting many benefits. Oracle is also introducing new Reactive Streams API in Java SE 9.

Java SE 9 Reactive Streams API is a Publish/Subscribe Framework to implement Asynchronous, Scalable and Parallel applications very easily using Java language.

Java SE 9 has introduced the following API to develop Reactive Streams in Java-based applications.

  • java.util.concurrent.Flow
  • java.util.concurrent.Flow.Publisher
  • java.util.concurrent.Flow.Subscriber
  • java.util.concurrent.Flow.Processor

CompletableFuture API Improvements

In Java 9, Oracle has done some implrovement into CompletableFuture API by adding to support some delays and timeouts, some utility methods and better sub-classing.

Executor exe = CompletableFuture.delayedExecutor(50L, TimeUnit.SECONDS);

Here delayedExecutor() is static utility method used to return a new Executor that submits a task to the default executor after the given delay.

Stack Walking

The stack is a Last-In-First-Out data structure. In terms of the Java Virtual Machine, a stack is required to store frames. Each time a new method is put to use, a latest frame is developed and added to the top level of the stack. A frame is abolished or propped out of the stack when the process of invocation is completed. Every frame on a stack consists of its own set of variables, along with its own stack, return value.

Up until Java 8, StackTraceElement represented a stack frame, Thread.getStackTrace( ) was being used to access the complete stack and Throwable.getStackTrace( ). An array of StackTraceElement was returned that you could iterate to get desired information.

But with the release of Java 9, a latest class ‘StackWalker’ has been introduced. It simpler and effective stack walking utilizing sequential. The StackWalker class is very efficient because it emerges the stack frames slowly.

Java Docs Updates

The new Java 9 improves the javadoc tool to create HTML5 markup. It for now generates pages in HTML 4.01.
The command that needs to be run is:

javadoc [options] [packagenames] [sourcefiles] [@files]

HTML5 uses a simpler structure. For accessibility, it implements the WAI-ARIA. The goal is to make things simpler for users with physical or visual impairments to access Javadocs pages using tools like screen readers. One of the examples for that is given below:

JEP 225 enables the ability to look up a Javadoc for program elements and keywords.

The below would become searchable:

  • Packages
  • Types and members
  • Declared names of modules
  • The simple name of method parameter types

Multi-release JARs

In Java 9, it is also a very interesting feature. And this feature will help library maintainers. Suppose a new version of Java comes in the market. Sometimes, it takes a lot of time to change your APIs with a new version of Java. In this case, we have to provide old version compatibility to the API to support the old java version such as 5, 6 and 7. That means you are not able to use new Java 9 for a long time. But in Java 9, don’t worry about this delay, fortunately, the multi-release JAR feature allows you to create alternate versions of classes that are only used when running the library on a specific Java version:

doj.jar
├── META-INF
│   └── versions
│       └── 9
│           └── doj-jar
│               └── MyClass.class
├── doj-jar
    ├── MyClass.class
    └── Main.class

Miscellaneous Java 9 features

There are many more feature and enhancement in Java 9 version. I have discussed some them in this article of Java 9 features but other features as well as in Java 9, which I am listing down here for quick reference.

  • Try With Resources Improvement
  • Diamond Operator for Anonymous Inner Class
  • Enhanced @Deprecated annotation
  • Multi-Resolution Image API
  • GC (Garbage Collector) Improvements
  • Filter Incoming Serialization Data
  • Deprecate the Applet API
  • Modify String Concatenation
  • Enhanced Method Handles
  • Compact Strings
  • Parser API for Nashorn

Summary

With the release of Java 9, a comprehensive new release in the Java series, Java will acquire a new standard of advancement as a developer’s software. Java 9 brings in new features and enhances the ones that were introduced previously in Java 8.