Java 9 New Features
In this articles, we will be covering Java 9 new features at a high level. We will explore these features along with details as what are the improvements happening to the existing features.
Introduction
Java 8 introduced a couple of new and exciting features like lambdas, streams and some of the API changes, Java 9 is coming up with rich feature sets like Jigsaw, Jshell (REPL), collections and some API changes under the hood. In this, we will explore all Java 9 new features at a high level. You can get detail information of all Java 9 features available JDK 9.
1. Modular System – Jigsaw Project
The modular system is one of the main and defining features of the Java 9.Jigsaw is responsible for bringing modularity to the Java platform. One of the main reason to bring modularity to the Java provides modular JVM which can help us to run JVM on different devices with less memory.
In another way, it’s a mechanism to run only modules and API required by a given application (e.g.application 1 need 3 modules to run completely while application 2 need only 1 module). Modules will be defined/ described in a file called module-info.java located at the top of our Java code hierarchy.
In order to understand Java 9 Modular system, let’s take an example of the Order placement process where we need OMS (Order Management System) to place an order but for the rest of the use cases (e.g. Browsing site or adding products to the shopping cart), we might not need OMS for our application. We can have a web-based application which allows placing an order, however, we can have other channels which can place an order and we need an OMS module to process these orders correctly. To achieve this, we can define 2 modules in Java 9 and can define required dependencies
module com.javadevjournal.shop.order {
requires com.javadevjournal.erp.oms;
}
Here is a pictorial representation of the Java 9 Module system
Based on the requires statement, JVM will try to determine if it is able to resolve all modules. I strongly believe that Java 9 Modules feature will allow us to structure our application in a better way and will strongly enforce encapsulation and defined/ explicit dependencies.
2. JShell (REPL)
Many modern languages provide a tool (Mostly called as REPL or scripting tool) for real-time statement interpretation. One of the benefits of such tool is that you can easily test your code without creating a complete class or project.Java 9 is introducing REPL or JShell which is helpful to quickly run your code and compare results. For more details and video tutorial, please read Introduction to Java 9 REPL and JShell
3. G1 (Default Garbage Collector)
Java 8 has 4 different Garbage Collector and default Garbage Collector in Java 8 is Parallel / Throughput Collector. G1 will be the new default Garbage Collector in Java 9. G1 was designed for better performance and know to have less number of GC pauses. Get more insight of the all available Garbage Collectors and their feature in our other post Java Garbage Collector.
4. HTTP 2.0 Client
Java 9 is coming up with a new HTTP 2.0
based client which can also be taken as a replacement for the famous.HttpURLConnection
Java 9 will be providing full support for new HTTP 2.0
and this new client will be supporting both HTTP/2
protocol and WebSocket.
This new HTTP Client in Java 9 will be introduced as first incubator module in Java which means it will be introduced as an experimental feature and based on the feedback it will either be added as a full-featured module in next release or will be removed from the Java platform.
HttpClient client = HttpClient.newHttpClient();
HttpRequest request = HttpRequest.newBuilder()
.uri(new URI("www.travellingrants.com")).build();
HttpResponse<String> response = client.send(request,HttpResponse.BodyHandler.asString());
System.out.println(response.statusCode());
System.out.println(response.body());
It’s really easy and clean API, we no longer have to use InputStream
or Reader
and even our old friend.HttpURLConnection
.HTTP 2.0 API also support an Asynchronous call by simply using HttpClient#sendAsync()
method instead of HttpClient#send
method. There is also an option to cancel your request if server support HTTP/2.
For more details, please read HTTP Client in Java 9
5. StackWalker API
To put Stack Walk API in Java 9 in simple words, It provides capabilities to walk through the stack in Java. StackWalker provides a snapshot of the current thread stack trace along with some methods to access it.Please read our article StackWalker API In Java 9 to get more insight into this new Java 9 feature.
6. Process API
Before Java 9 there was a limited support for controlling and managing operating systems processes, even getting hold of simpler OS related process was not a simple one-liner solution and require a lot of workarounds.
Java 9 is introducing a lot of improvements to process API for controlling and managing OS related process.
java.lang.ProcessHandle class contains most of the new features of the process API. To get an understanding let’s take an example of getting PID in both Java 8 and Java 9
Java 8
public static void getProcessIdByJava8(){
try {
String[] args = new String[] { "/bin/sh", "-c", "echo $PPID" };
Process p = Runtime.getRuntime().exec(args);
InputStream p_out = p.getInputStream();
String s = (new BufferedReader(new InputStreamReader(p_out))).readLine();
p.destroy();
if (s != null)
System.out.println(s);
} catch (IOException e) {
e.printStackTrace();
}
}
Java 9
public static void getProcessIdByJava9(){
System.out.println("Your Process id is :" + ProcessHandle.current().pid());
}
As we saw, getting operating system information using Java 9 process API is quite easy and clean. It gives Java developer an API to interact with the operating system and can be used to get information on the status of the JVM. We can get a lot of other information from the process API. Read here for more details.
7. Collection Factory Methods
Collection Factory methods in Java 9 like Scala. Static methods have been provided by Java 9 on List, Set and Map interfaces which can easily returned unmodifiable collections by calling of() method of the respective interface.For more detail, please read Collection Factory Methods in Java 9
8. Try With Resources Improvement
Java 7 introduced try-with-resources for managing resources automatically and to ensure that resources will be closed after execution of the program.
Before Java 9, in order to use try-with-resources, we will have to use something like this
try (BufferedReader br = new BufferedReader(new FileReader("/input.txt"))) {
String line;
while (null != (line = br.readLine())) {
// processing each line of file
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
Or we will be using a very similar syntax, Above syntax provide a lot of features and auto management of the resources, however, we still need to declare a local variable to work with, Java 9 is a further refinement to this feature to avoid verbosity.
BufferedReader br = new BufferedReader(new FileReader("/input.txt"));
// Java 9 make it simple
try (br) {
String line;
while (null != (line = br.readLine())) {
// processing each line of file
System.out.println(line);
}
} catch (IOException e) {
e.printStackTrace();
}
9. Interface Private Method
Java 8 came with certain enhancement while declaring interfaces, few of those features are
- Method implementation in interface using default and static methods
However, it still not provide a way to create a private method in Interface. Java 9 will provide a way to have a private method in an interface. This feature will really be useful to avoid redundant code and promote code reusability.
public interface PrivateMethodExample {
private static String getDBDetails(){
return "MySQL";
}
private boolean checkConnection(String DBDetails){
return DBDetails.equalsIgnoreCase("MySQL") ? true : false;
}
default void checkDBConnection(){
String dbName = getDBDetails();
boolean isAlive = checkConnection(dbName);
}
}
10. Мulti-Resolution Image API
Java 9 introducing a new API under java.awt.image package, it allows a set of images with different resolutions to be encapsulated into a single multi-resolution image. For more details read Multi-Resolution Images.
11. CompletableFuture API Improvements
Java 9 have done improvements to the CompletableFuture API. JDK 9 added timeout option to the CompletableFuture API. This is really helpful while dealing with the asynchronous API. You can specify the behavior of this APi after a user-defined period.
Executor exe = CompletableFuture.delayedExecutor(50L, TimeUnit.SECONDS);
CompletableFuture came with copy()
method that returns an immutable copy of an existing CompletableFuture.This is also helpful while dealing with the asynchronous API that returns CompletableFutures.
CompletableFuture future = new CompletableFuture<>();
future.copy();
12. Optional Class Improvements
Java 8 brings the Optional API. They are really helpful to avoid NullPointerExceptions if used correctly. Let’s take a look at some of the most important changes done in Java 9 for the Optional API.
- Java 9 added
stream()
method to the Optional API.Optional::stream
allows you to transform anOptional
to aStream
. - The
or()
method either returns the currentOptional
if a value is present or anOptional
by the provided supplier function is returned. - Last addition is the
ifPresentOrElse
method.
13. Miscellaneous Java 9 Features
There are other features introduced in Java 9 which I will be covering in another post in more details, here is the list of some of the other features introduced in Java 9
- Unified JVM Logging.
- Stream API Improvement.
- Reactive Streams
- Improved Javadoc
Summary
In this post, we covered Java 9 new features. Java 9 is coming up with modular JVM which is going to be one of the defining features of Java 9 along with a number of improvements in the JDK.
Comments are closed.