Java 9 Features

Just like Java 8 is known as the major release of lambdas, streams and API changes, similarly Java 9 is all about project Jigsaw, utilities and changes under the hood. In this post, I would like to talk about some of the most exciting features being targeted for Java 9. The full list of new features is available here.

Modular System – Jigsaw Project

This is the biggest addition to the JDK and would bring modularity to the Java platform. An increase in codebase, quite often leads to complicated, tangled “spaghetti code”. It makes it hard to encapsulate code and there is no clear dependencies between different parts (JAR files) of a system. Any public class can access any other public class based on the classpath. This can lead to inadvertent usage of classes that were not supposed to be public API. In fact, the classpath itself is not an elegant way of verifying if the required JARs are present or it there are any duplicate entries. These challenges are handled very well by the module system.

The capabilities of a modular system are quite similar to those of OSGi framework. Modules have an inherent concept of dependencies, can expose a public API and keep implementation details hidden/private. The biggest motivation is to provide modular JVM, which requires lesser memory footprint in order to run on devices. The JVM can then run with only those modules and APIs which are essential.

There is an additional module descriptor in modular JAR files. This module descriptor, has dependencies expressed through “requires” statements. In addition to this, “exports” statements control which packages are accessible to other modules.

Modular JAR files contain an additional module descriptor. In this module descriptor, dependencies on other modules are expressed through “requires” statements. Additionally, “exports” statements control which packages are accessible to other modules. All packages which are not exported are encapsulated in the module by default. Let’s see an example of a module descriptor, which lives in `module-info.java`:

module com.thistechnologylife.java9.modules.house {

requires com.thistechnologylife.java9.modules.furniture;

exports com.thistechnologylife.java9.modules.lawn;

}

The module house requires module furniture and exports a package for lawn.

JShell – The Interactive Java REPL

Jaba 9 comes with a new tool called “jshell”, which stands for Java Shell and also known as REPL (Read Evaluate Print Loop). It can be used to execute and test any Java Constructs like class, interface, enum, object, statements etc. very easily without wrapping them in a separate method or project.

JShell can be launched directly from the console and you can start typing and executing Java code. One great example of jshell is to test regular expressions.

The jshell executable itself can be found in <JAVA_HOME>/bin folder:

jdk-9\bin>jshell.exe

| Welcome to JShell -- Version 9

| For an introduction type: /help intro

jshell> "Say Hello To Java 9 Features".substring(13,19);

$5 ==> "Java 9"

Improved Network Communication with HTTP/2.0 Support

Java 9 comes with a new way of performing HTTP based communication. It provides a long-awaited replacement of the old HttpURLConnection and supports both WebSockets and HTTP/2. The new API is located under the java.net.http package.

HttpClient client = HttpClient.newHttpClient();

HttpRequest request =

HttpRequest.newBuilder(URI.create("http://www.amazon.com"))

.header("User-Agent","Java")

.GET()

.build();

HttpResponse<String> response = client.send(request, HttpResponse.BodyHandler.asString());

HttpClient also provides new APIs to deal with HTTP/2 features such as streams and server push.

Enhanced Process API

Process API had a limited capability to control and manage operating system processes. Even for getting process PID, you would need to either use native code or a tricky workaround. Not to forget, you would need different implementation for each platform.

In Java 9, the process API has been enhanced for controlling and managing operating-system processes. Most of the new functionality is present in the class java.lang.ProcessHandle. Process specific information can be obtained in the following manner:

ProcessHandle procHandle = ProcessHandle.current();

long PID = procHandle.getPid();

ProcessHandle.Info processInfo = procHandle.info();

Optional<String[]> args = processInfo.arguments();

Optional<String> cmd = processInfo.commandLine();

Optional<Instant> startTime = processInfo.startInstant();

Optional<Duration> cpuUsage = processInfo.totalCpuDuration();

As the example illustrates, the current method returns an object representing a process of currently running JVM. The Info subclass provides details about the process.

Now let’s see how we can stop all running processes using destroy method:

childProcess = ProcHandle.current().children();

childProcess.forEach(procHandle -> {

assertTrue("Could not kill process " + procHandle.getPid(), procHandle.destroy());

});

Stream API improvements

Java 9 brings significant improvements to the Stream API which packs a punch in creation of declarative pipelines of transformations on collections. Four new methods have been added to the java.util.Stream interface – dropWhile, takeWhile, ofNullable. The iterate method gets a new overload, which helps in providing a Predicate on when to stop iterating.

The takeWhile method takes a predicate as an argument and returns a Stream of subset of the given Stream values until that Predicate returns false for first time. If first value does NOT satisfy that Predicate, it just returns an empty Stream.

In this post I have tried to give a glimpse of some of the newly introduced features in Java 9. Trust me, we have just scratched the surface and there are many more useful and diverse features which would be available with Java 9. I am quite excited about this. What about you?

Please follow and like us:
RSS20
Follow by Email
Facebook0
Google+20
http://www.thistechnologylife.com/?p=422
Twitter20
LinkedIn25

Leave a Reply

Your email address will not be published. Required fields are marked *