The 9 New Developer Features in Java 9
The big new features in JDK 9 is the Java Platform Module System coupled with the introduction of the modular JDK. However, there are plenty of new features in JDK 9, and in this article, I focus on nine that are of particular interest to developers. Where applicable, I've included the relevant JDK Enhancement Proposal (JEP) numbers so you can find more information.
No 1.
Factory Methods for Collections (JEP 269)
Collections provide a well-understood way for you to gather together groups ( I was going to say sets, but that could be a bit misleading) of data items in your applications and then manipulate the data in a variety of useful ways.At the top level, there are interfaces that represent the abstract concept of a List, Set, and Map.
The problem, until now has been that Java doesn't provide a simple way to create a collection with predefined data. if you want a collection to be structurally immutable (that is, you can't add, delete, or change the reference to elements), you need to do more work.
Let's look at a simple example using JDK 8.
List<Point> myList = new ArrayList<>();
myList.add(new Point(1,1));
myList.add( new Point(2,2));
myList.add( new Point(3,3));
myList.add( new Point(4,4));
myList = Collections.unmodifiableList(myList);
It's not terrible, admittedly, but to create an immutable list of four Points required six lines of code. JDK 9 addresses this through factory methods for collections.
This feature makes use of a change introduced in JDK 8 that enabled static methods to be included in interfaces. That change means that you can add the necessary methods to the top-level interfaces (Set, List, and Map) rather than having to add them to a large group of classes that implement those interfaces.
Let's rewrite our example using JDK 9
List<Point> list =
List.of(new Point(1,1), new Point(2,2), new Point(3,3), new Point(4,4));
This code is much simpler!!
The rules that apply to the use of the different collections also apply( as you would expect) when using these factory methods. So, you cannot pass duplicate keys when you create a Map. A null value cannot be used as a value for any collection factory method. The Javadoc documentation provides full descriptions of how the methods may be called.
The Optional class was introduced in JDK 8 to reduce the number of places where a NullPointerException could be generated by the code ( and it was frequently used to make the Stream API more robust).
JDK 9 adds four new methods to Optional:
No.2.
Optional Class Enhancements
The Optional class was introduced in JDK 8 to reduce the number of places where a NullPointerException could be generated by the code ( and it was frequently used to make the Stream API more robust).
JDK 9 adds four new methods to Optional:
- ifPresent(Consumer action): if there is a value present perform the action using the value.
- ifPresentOrElse(Consumer action, Runnable emptyAction): Similar to ifPresent, but if there is no value, it executes the emptyAction.
- or(Supplier supplier): This method is useful when you want to ensure that you always have an Optional. The or() method returns the same Optional if a value is present; otherwise, it returns a new Optional created by the Supplier.
- stream(); Returns a stream of zero or one elements depending on whether there is a value.
No.3.
Stream API Enhancements
It's always useful to be able to create a stream sourced from a collection of data, and JDK 8 provided several methods to do this outside the Collection API (BufferedReader.lines(), for example). Several new sources are being added in JDK 9, such as java.util.regex.Matcher.
JDK 9 adds four methods to the Stream interface. First there are two related methods:takeWhile(Predicate) and dropWhile(Predicate). These methods are complementary to the existing limit() and skip() methods but they use a Predicate rather than a fixed integer value. The takeWhile() method continue to take elements from the input stream and pass them to the output stream until the test() method of the predicate returns true.
No.4.
Read-Eval-Print Loop; shell (JEP 222)
JDK 9 includes a new read-Eval-print loop(REPL) command line tool, jshell, that allows you to develop and test Java code interactively, unlike when you use an IDE, where code must be edited, compiled, and then run. Developers can quickly prototype sections of code as jshell continually reads user input, evaluates it, and prints either the value of the input or description of the state change the input caused.
To make the tool easier to use, it includes features such as an editable history, tab completion, automatic addition of terminal semi colons when needed and configurable predefined imports and definitions. It is also possible to declare variables whose type is defined after the declaration(but this is still not dynamic typing: once the type is set, it can’t be changed).
There is even a module,jdk.jshell, that can be used if you want to build your own “snippet” evaluation tool.
No.5.
Concurrency Updates(JEP 266)
Java 5 introduced concurrency utilities to simplify writing Java code that has multiple cooperating threads.Subsequent releases have improved these features by adding things such as the fork/join framework in JDK 7 and, most recently, parallel streams in JDK 8.Now, JDK 9 provides enhancements for concurrency in two areas. The first is a reactive stream publish-subscribe frame work. Processing streams of elements in an asynchronous fashion can lead to problems when the rate at which elements are submitted to the processing code rises sharply. If the processor is unable to handle the load, the elements supplier can be blocked or a buffer overflow situation can occur.
JDK 9 includes new classes, Flow, that encloses several interfaces: Flow.Processor, Flow.Subscribe, Flow.Publish and Flow.Subscription. A Subscription is used to link a Publisher with a Subscriber.
The subscription interface contains two methods:
· cancel(): This method causes the Subscription to stop receiving messages(eventually).
· request(long n): Add n elements to the number that the Subscriber is also able to process. This method can be called repeatedly as the Subscriber processes elements and is ready to process more.
No.6.
Milling Project Coin(JEP 213)
One of the most significant changes in JDK 7 was the Project Coin, which was a set of small language changes to smooth out some of the common tasks developers undertake repeatedly in Java. The project included things such as the ability to use Strings as constants in switch statements.JDK 9 builds on this and adds a few more small changes to the language syntax of Java.
· Effectively final variables can be used in try-with-resources without being reassigned.Concurrently, each resources that are used must be assigned to a new variable, even if that resource has already been defined in the method. With this change, it is now possible to use an existing variable(as long as it is effectively final) without reassigning it. Here is an example of the change.
try(Resource r = alreadyDefinedResource) …
in JDK 9 it becomes
try(alreadyDefinedResource) …
· Private methods can be used in interfaces.Interfaces change in a big way in JDK 8.First, there was the introduction of default methods, which allowed new methods to be added to existing interfaces without forcing a break in backward compatibility. Because this meant that behavior could be included in an interface ( giving Java multiple-inheritance of behavior for the first time).
· The Diamond operator can be used with anonymous inner classes. List<String> myList = new ArrayList<>() { // Overridden methods };
· A single underscore will no longer be valid as an identifier.
· Extended use of the @SafeVarargs annotation is allowed. Currently, this annotation can be used only on constructors, static methods, and final methods, none of which can be overridden. Because a private method cannot be overridden by a subclass, it is logical also to enable private methods to use this annotation.
No.7.
Spin-Wait Hints(JEP 285)
One of the most significant changes in JDK 9 cost by modularizing the core JDK libraries is the encapsulation of the internal APIs by default. Probably the most well known of these is sun.misc.Unsafe. To make some of the functionality of these private API available through a public API JDK 9 introduces the VarHandle class.
ProcessBuilder ls = new ProcessBuilder()
.command(“ls”)
.directory(Paths.get(“/tmp”).toFile());
ProcessBuilder wc = new ProcessBuilder()
.command(“wc”, “-1”)
.redirectOutput(Redirect.INHERIT);
List<Process> LsPipeWc = ProcessBuilder.startPipeline(asList(ls,wc));
No.8.
Variable Handles(JEP 193)
One of the most significant changes in JDK 9 cost by modularizing the core JDK libraries is the encapsulation of the internal APIs by default. Probably the most well known of these is sun.misc.Unsafe. To make some of the functionality of these private API available through a public API JDK 9 introduces the VarHandle class.
Variables are used in Java all the time. They are implicit pointers to areas of memory that hold values. A variable handle is a typed reference to a variable(so far those who’ve used C and C++, it’s effectively a pointer to a pointer).
No.9.
Process API Updates (JEP 102)
JDK 9 contains enhancements to the Process and ProcessBuilder classes and introduces a new ProcessHandle interface. ProcessBuilder now includes the method startAsPipeline(). As the name suggests, this method constructs a UNIX-style pipeline of processes using a list of ProcessBuilders. As each process is started, its standard output is connected to the standard input of the next process.
Here is a simple example that pipes the output of the UNIX/Linux ls command on /tmp through wc -1 to get a count of the number of files in the tmp directory:
.command(“ls”)
.directory(Paths.get(“/tmp”).toFile());
ProcessBuilder wc = new ProcessBuilder()
.command(“wc”, “-1”)
.redirectOutput(Redirect.INHERIT);
List<Process> LsPipeWc = ProcessBuilder.startPipeline(asList(ls,wc));
Conclusion
As is clear, there are many useful and powerful new features included in JDK 9 that are particularly targeted at developers. With features such as these, you might want to consider migrating your development to this release as soon as you can.

Comments
Post a Comment