Introduction To Java 9 Features
1. Overview
In this post, I would like to introduce features that have been come up with JDK 9.Some of the major features are module system (jigsaw), Jshell(REPL), Collection Factory Methods, a private method in the interface, compact string, try with resources improvement, HTTP Client, Reactive Stream, Optional Class improvement, Stream API improvement. Let's look each in brief.2. Module System
Quoting overview of Module by Oracle chief architect Mark Reinhold:A module is a named, self-describing collection of code and data. Its code is organized as a set of packages containing types, i.e., Java classes and interfaces; its data includes resources and other kinds of static information.
To control how its code refers to types in other modules, a module declares which other modules it requires in order to be compiled and run. To control how code in other modules refers to types in its packages, a module declares which of those packages it exports
If we take a look at JDK 8 or earlier versions we saw JDK itself is too big and it scale down small devices like IOT Devices.So whether you have used JDK library classes which reside on rt.jar, tool.jar etc, you have to put whole JDK in the classpath. To overcome such problem Java 9 come up with module system where you can build your own run-time image.
One of the main goals of Module System is to bring strong encapsulation.With the help of Module System, we can define which parts of code available to other modules.It also modularize JDK so Instead of a monolithic library, JDK 9 divided JDK into modules. there are around 98 modules in JDK. Module system allows us to build own JDK runtime image.
For Further Reference:
Exploring-Java-9-Java-Platform-Module-System
Java-9-modules-tutorial
3. Java 9 REPL (JShell)
JDK 9 come up with new command line tool called "JShell" (Java Shell).It enables developers to use a read–eval–print loop (REPL) interface that help for learning and testing code java 9 code snippet.[code language="java"]
java> System.out.println("Welcome to Jshell");
Welcome to Jshell
java> int a=10
int a = 10
java> System.out.println("Value of a="+a);
Value of a=10
java>
[/code]
For Further Reference:
<a href="https://developers.redhat.com/blog/2017/10/03/use-jshell-command-line-tool-introduced-jdk-9/">Use-jshell-command-line-tool-introduced-jdk-9 </a>
<a href="https://youtu.be/op6zZDypPg8">You can watch the demo by JShell with Yoshida Shinya</a>
4. Factory Methods
JDK introduced some convenient factory methods to create Immutable List, Set, Map and Map.Entry objects. Prior to JDK 9, Create immutable collection is very verboseLet's see the different way to create immutable collection prior to JDK 9.Simple Way to create Unmodifiable List.
[code language="java"]
List&amp;amp;amp;lt;String&amp;amp;amp;gt; colorsList = new ArrayList&amp;amp;amp;lt;&amp;amp;amp;gt;();
colorsList.add("Red");
colorsList.add("Green");
colorsList.add("Blue");
colorsList = Collections.unmodifiableList(colorsList);
[/code]
Using double-brace technique:
[code language="java"]
List&amp;amp;amp;lt;String&amp;amp;amp;gt; colorsList =
Collections.unmodifiableList(new ArrayList&amp;amp;amp;lt;String&amp;amp;amp;gt;(){{
add("Red"); add("Green"); add("Blue");
}});
[/code]
As we have seen above all of above approach to creating unmodifiableSet is verbose. Let see the new way to create an immutable collection with JDK 9.
Signature :
[code langular="java"]
static &amp;amp;amp;lt;E&amp;amp;amp;gt; Set &amp;amp;amp;lt;E&amp;amp;amp;gt; of(E e1, E e2, E e3)
[/code]
<strong>Example :</strong>
[code language="java"]
List&amp;amp;amp;lt;String&amp;amp;amp;gt; list = List.of("Red", "Green", "Blue");
[/code]
<strong>For Further Reference:</strong>
<a href="http://www.baeldung.com/java-9-collections-factory-methods">Baeldung wrote nice post-Java-9-collections-factory-methods</a>
5. Private methods in Interfaces
Prior to JDK 8, interfaces are simple. They contain only public abstract method. JDK 8 changed this by allowing static as well as default method
Default Method JDK 8 :
[code language="java"]
public interface IUser{
// default method,
public default User getUserByName(String name) {
// getting a user with DAO.
}
}
[/code]
However, we cannot create private method prior to JDK 9.JDK 9 allows us to create the private method to avoid redundant code and more re-usability.
Private Method JDK 9 :
[code language="java"]
public interface IUser{
// default method,
public default User getUserByName(String name) {
// getting user with DAO.
}
private void checkUserIsActive(String name) {
// code to check user is active or not
}
}
[/code]
For Further Reference:
<a href="https://www.journaldev.com/12850/java-9-private-methods-interfaces">Java-9-private-methods-interfaces</a>
6. Compact String
In any of the Java applications Strings are used extensively.prior to JDK 9 , each character of string occupied 2 bytes irrespective of characters encoded in ISO-8859-1/Latin-1 or UTF-16 though ISO-8859-1/Latin-1 characters required only 1 byte for each character. So from JDK 9 ISO-8859-1/Latin-1 represented with only 1 byte whereas UTF-16 encoded characters represented by 2 bytes.
For Further Reference:
<a href="http://www.baeldung.com/java-9-compact-string">Baeldung wrote nice post on compact string</a>
<a href="https://arnaudroger.github.io/blog/2017/06/14/CompactStrings.html">CompactStrings</a>
<a href="http://vojtechruzicka.com/java-9-compact-strings/">Java-9-compact-strings</a>
<a href="https://www.javagists.com/compact-strings-java-9">Compact-strings-java-9</a></div>
7. Try With Resources Improvement
From JDK 7 resources automatically managed (like close resultset, close I/O resources) using try-with-resource block. Any class used try-with-resource must implement java.lang.AutoCloseable interface otherwise compiler gives an error message.
[code language="java"]
public static void main(String args[]) throws IOException {
File file = new File("/Users/admin//try-with-resource.txt/");
try( BufferedReader bufferedReader =
new BufferedReader(new FileReader(file))){
String st = bufferedReader.readLine();
System.out.println(st);
}
}
[/code]
So here we need to create the resource within try-with-resource block only. JDK 9 improve resource statement and allowed to manage resource outside the try-with-resource unless and until it is final or effectively final.
[code language="java"]
public static void main(String args[]) throws IOException{
File file = new File("/Users/admin//try-with-resource.txt/");
BufferedReader bufferedReader= new BufferedReader(new FileReader(file))
try(bufferedReader){
String st = reader.readLine();
System.out.println(st);
}
}
[/code]
For Further Reference:
<a href="http://javasampleapproach.com/java/java-9/java-9-try-resources-improvement.">Java-9-try-resources-improvement</a>
8. HTTP Client
Java’s existing HttpURLConnection has some problems. It is hard to use, in part from being abstracted to work with multiple protocols (like FTP and Gopher). It turns out 20 years later that HTTP was the big winner in protocol land. But the biggest problem is that HttpURLConnection works only in blocking mode so there is only one thread per request/response.
There are other HTTP clients out there that solve some of these problems, such as <a href="http://www.eclipse.org/jetty/documentation/current/http-client-api.html">Jetty</a> and the <a href="https://hc.apache.org/httpcomponents-client-ga/">Apache HttpClient</a>. Jetty even has a non-blocking mode. However, both of these are sizeable libraries to bring in, and neither take advantage of lambdas
Get Request :
[code language="java"]
HttpRequest request =
HttpRequest.create(new URI("http://localhost:8080")).GET();
String responseBody = response.body(request.response().asString())
[/code]
Async HTTP Request :
[code language="java"]
HttpRequest httpRequest = HttpRequest
.create(new URI("http://www.google.com"))
.body(noBody())
.GET();
CompletableFuture&amp;amp;amp;lt;HttpResponse&amp;amp;amp;gt; completableFutureHttpResponse =
httpRequest.sendAsync();
if (!completableFutureHttpResponse.isDone()) {
completableFutureHttpResponse.cancel(true);
System.out.println("Async call Failed...");
return;
}
HttpResponse httpResponse = completableFutureHttpResponse.get();
[/code]
For Further Reference:
<a href="https://blogs.oracle.com/java/jdk-http-client">Oracle wrote good blog on HttpClient</a></div>
9. Reactive Streams
Reactive Programming become popular nowadays. It allow us to develop application in non-blocking mode. Many popular framework like Spring (Support from Spring 5), Scala, Akka etc has already integrated it. Oracle corps has been added Reactive Stream API in JDK9.
Further reading:
<a href="http://www.baeldung.com/java-9-reactive-streams">baeldung wrote nice post on reactive stream </a>
<a href="https://community.oracle.com/docs/DOC-1006738">Reactive Stream Article By Oracle.</a>
10. Optional Class Improvements
<a href="http://www.baeldung.com/java-optional">Java 8 introduce Optional class</a>. The purpose of this class set option value instead of null reference to prevent null pointer exception.Apart from this JDK 9 improved Optional class by adding some useful methods. Let’s look each by example.
10.1. ifPresentOrElse() Method
It’s a common thing where we want to perform a task if value present for Optional instance otherwise take different action in absent of value in Optional.
instance.
<strong>Syntax :</strong>
[code language="java"]
void ifPresentOrElse (Consumer&amp;amp;amp;lt;? super T&amp;amp;amp;gt; action, Runnable emptyAction);
[/code]
<strong>Example :</strong>
[code language="java"]
lookupUser(user)
.ifPresentOrElse(
this::getUserDetails,
this::sendErrorMessage);
[/code]
<h3><strong>10.2. </strong><strong>or() Method</strong></h3>
In case of Optional instance empty , we want to perform task which also return Optional. JDK 9 add orElse() and orElseGet() methods but it returns instance (not Optional instance).
<strong>Syntax :</strong>
[code language="java"]
public Optional or (Supplier&amp;amp;amp;lt;? extends Optional&amp;amp;amp;lt;? extends T&amp;amp;amp;gt;&amp;amp;amp;gt; supplier);
[/code]
<strong>Example:</strong>
[code language="java"]
Optional user =
findUser(username)
.or(() -&amp;amp;amp;gt; createUserByUsername(username))
[/code]
10.3. stream() Method
JDK 9 introduce new method in Optional class i.e stream(). It allows to perform stream operation on Optional class. If value present in Optional instance it returns a stream containing only that value otherwise returns an empty stream.
[code language="java"]
java&amp;amp;amp;gt; Optional.of("Red","Green","Blue").stream().forEach(System.out::println);
Red
Green
Blue
java&amp;amp;amp;gt; Optional.empty().stream().forEach(System.out::println)
//does not print anything as return empty stream
[/code]
For Further Reference:
<a href="http://www.baeldung.com/java-9-optional">baeldung post java 9 optional</a>
<a href="http://iteratrlearning.com/java9/2016/09/05/java9-optional.html">Iteratrlearning post java 9 optional</a></div>
11. Stream API Improvements :
One of the most powerful features that JDK 8 introduced is Stream API. JDK 9 make it better by adding new methods like takeWhile(), dropWhile(), iterate(), and ofNullable().
11.1. takeWhile() Method
It works as same as limit() function that was introduced in jdk8. But doesn’t take a predicate.
<strong>Syntax :</strong>
[code language="java"]
default Stream takeWhile (Predicate&amp;amp;amp;lt;? super T&amp;amp;amp;gt; predicate)[/code]
<strong>Example:</strong>
[code language="java"]
java&amp;amp;amp;gt; List numberList = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
numberList ==&amp;amp;amp;gt; [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
java&amp;amp;amp;gt; numberList.stream().takeWhile(number -&amp;amp;amp;gt; number &amp;amp;amp;lt;= 5).forEach(System.out::println)
1
2
3
4
5
[/code]
11.2. dropWhile()
It works same as skip() function that has been introduced in JDK8. The only difference is it won't take predicate
<strong>Syntax :</strong>
[code language="java"]
default Stream dropWhile (Predicate&amp;amp;amp;lt;? super T&amp;amp;amp;gt; predicate)
[/code]
<strong>Example:</strong>
[code language="java"]
java&amp;amp;amp;gt; List numberList = List.of(1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
numberList ==&amp;amp;amp;gt; [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
java&amp;amp;amp;gt; numberList.stream().dropWhile(number -&amp;amp;amp;gt; number &amp;amp;amp;lt;= 5).forEach(System.out::println)
6
7
8
9
10
[/code]
11.3. iterate() Method
iterate has been overloaded in JDK9 to support finite stream.
<strong>Syntax :</strong>
[code language="java"]
//Prior to JDK 9
static Stream iterate(final T seed, final UnaryOperator f)
//JDK9
static Stream iterate(T seed, Predicate hasNext, UnaryOperator next)
[/code]
<strong>Example: </strong>
[code language="java"]
java&amp;amp;amp;gt; Stream.iterate(1, i -&amp;amp;amp;gt; i &amp;amp;amp;lt;= 5, i -&amp;amp;amp;gt; i+1).forEach(System.out::println)
1
2
3
4
5
[/code]
11.4. ofNullable()
It return sequential Stream containing a single element if not null, otherwise returns an empty stream
<strong>Syntax : </strong>
[code language="java"]static Stream ofNullable (T t)[/code]
<strong>Example:</strong>
[code language="java"]// Produces a Stream of Single element
java&amp;amp;amp;gt; Stream.ofNullable("Welcome to JDK9").forEach(System.out::println)
Welcome to JDK9
// Produces an empty Stream
java&amp;amp;amp;gt; Stream.ofNullable(null).forEach(System.out::println)
[/code]
For Further Reference:
<a href="https://www.callicoder.com/java-9-stream-api-enhancements/">java-9-stream-api-enhancements</a>
<a href="https://huongdanjava.com/method-ofnullable-stream-object-java.html">method-ofnullable-stream-object-java.html</a>
<a href="http://www.baeldung.com/java-9-stream-api">java-9-stream-api</a></div>
12. Conclusion
In this article, we have seen some of the major features introduced with JDK9. Below are some references of books and videos to get more functional details associated with JDK9.
Books :
<a href="https://www.amazon.in/Java-Modularity-Developing-Maintainable-Applications-ebook/dp/B075FZK9DC?tag=googinhydr18418-21">Java 9 Modularity: Patterns and Practices for Developing Maintainable Applications </a>
<a href="https://www.amazon.in/Core-Java-SE-9-Impatient/dp/0134694724">Core Java SE 9 for the Impatient</a>
<a href="https://www.amazon.com/Effective-Java-3rd-Joshua-Bloch/dp/0134685997/">Effective Java (3rd Edition)</a>
Videos:
<a href="https://www.youtube.com/watch?v=CMMzG8I23lY">55 New Features in JDK 9 by Simon Ritter</a>
<a href="https://www.youtube.com/watch?v=GkP83hvdeMk">Real World Java 9 by Trisha Gee</a>
<a href="https://www.youtube.com/watch?v=8XmYT89fBKg">Exploring Java 9 by Venkat Subramaniam </a>
<a href="https://www.youtube.com/watch?v=M7q3C8OwJe8&list=PLX8CzqL3ArzUPNQ-r1ZmJrSuoL2EVnVma">Migrating to Modules by Oracle (Play List)</a></div>
Comments
Post a Comment