The Object-Oriented Programming, Java was designed by James Gosling and Java was maintained by Oracle Corporation (then Sun Corporation). This general-purpose programming language is class-based and is equipped with concurrent programming features. Additionally, it also has multi-threading features, is a static, safe, and strongly typed programming language. The file extension names of this programming language are .java or .class.
The release of Java 9 is a milestone for the Java ecosystem. Staying up to date with new releases is essential to keep up with the technology and learning more about the released versions will gear you closer to your Java, J2EE & SOA Certification. In this article, we will talk about Java 9 features. Java 9’s initial version was released on 21 Sep 2017 and delivers exceptional improvements and new enhancements to the previous versions of Java. Java 9 guarantees that your coding methods and habits are extensively modified and updated in a way that benefits facilitate you. The most prominent difference brought forth by Java 9 is the modularization of Java. This is one of the important developments brought in Java programme after the onset of Lambdas in Java 8.
Java 9 is equipped with top-notch feature sets like Jshell (REPL), Jigsaw, collections, and some API changes under the hood. In this article, we will explore all Java 9 new features extensively. Before we explain the Java 9 features in detail let us take a quick glimpse at how Java 9 helped to overcome those anomalies present in the previous versions.
- In the previous version, the JDK and the Java Standard Edition platform were not navigable for small computing devices
- There was no overall security and maintenance of JDK.
- There was also a lack in the overall improvement in application performance
- For both the Java SE and EE Platforms, it was challenging for Java developers to develop and uphold the code libraries and larger applications.
- Java 9 deprecates a few features which are no longer in trend. The most important among those is Applet API. This feature has gone out of style as security-conscious developers have been removing support for Java browser plug-ins. Developers have now resorted to alternatives like Java Web Start, for launching apps from a browser.
- Java 9 also removes the feature of Concurrent Mark Sweep (CMS) garbage collector. The idea is to race up the growth of other garbage collectors in the HotSpot virtual machine.
- Java 9 also omits Java warnings on import statements. It helps to make large codebases clear of lint warnings.
Benefits of Java 9
Whether working with Java SE 9 or any other version, depending upon the business need, the addition of the most advanced features will bring forth advancements in the following:
- Greater speed of development, especially owing to the system of modules that are much easier to debug and maintain and are also reusable.
- Another advantage of the system of modules is that it will increase the resource effectiveness of big or small applications. The development programmers will require to take only required modules instead of all JRE.
- Formulation of sets using one instead of several lines of code.
- Microbenchmarks that will enable analyze the performance of very small pieces of code.
- Support for HTTP 2.0 Client – implying greater speed.
Top Java 9 Features
Let us look at some of the features which are an absolute must know about in Java 9:
Project Jigsaw in Java 9
The foremost purpose of this project is to acquaint everyone with the theory of modularity; support for formulating modules in Java 9 and then apply the same to the JDK i.e modularize the JDK.
Here are some of the advantages of modularity :
- Strong encapsulation: Only those parts of the module can be accessed that are made available for use. Hence, the public classes in a package are not free unless the package is exported in the module-info file.
- Clear Dependencies: Modules have to reveal which other modules they would be working on with the help of the required clause.
- Linking modules to generate a smaller runtime, which can be efficiently scaled to smaller computing devices.
- Reliable: Apps are more reliable by reducing run-time errors. For example- you must have encountered your apps collapsing during run-time owing to missing classes, resulting in ClassNotFoundException.
There are several JEPs (JDK Enhancement Proposals), which are a part of this project, like:
- JEP 200 – modular JDK: This pertains to the Java platform module system, which modularizes the JDK into a set of modules that can be consolidated at compile-time, build time, or runtime.
- JEP 201 – modular source code: The JDK source code is modularized into modules and improves the build tools to gather the modules.
- JEP 220 – modular runtime images: Helps in restructuring the JDK and JRE runtime images to make room for modules and to enhance safety, performance, and maintainability.
- JEP 260 – Enclose most internal APIs: A lot of internal APIs can be obtained directly or by reflection with the help of JEP 260. Accessing internal APIs that are subject to change is pretty tricky. To prevent its use, they are being enclosed into modules and only those internal APIs that are extensively used are made free until a fitting API is in its place.
- JEP 261 – module system: The objective of JEP 261 is to implement the new module system for the Java platform. The modular system was designed to provide secure configuration and effective encapsulation for Java programs.
- JEP 282: jlink, the Java linker: This enables packaging modules and their dependencies into smaller run times.
Noteworthy API Updates: Stack Walking and Concurrency
One of the JEPs that Oracle has initiated is JEP 266: More Concurrency Updates. The update holds some importance and can solve interesting problems in parallelism and concurrency, which require updates in those libraries.
The changes and updates will be:
- Interfaces upholding the Reactive Streams publish-subscribe framework
- Extensive enhancements implemented to the CompletableFuture API like support for timeouts, delays, subclassing, and other methods
- Overall developments like small tweaks and javadoc spec rewording
Next, let us talk about the concurrency updates of Java 9 with CompletableFuture and java.util.concurrent.Flow. Flow is considered as the Java implementation of the Reactive Streams API. Reactive Streams resolve the pain of back-pressure. The build-up of data occurs when the rate of the incoming task is higher than the app’s ability to process them, which results in a buffer of unhandled data. As a part of the concurrency updates, CompletableFuture will be updated as well. This will fix the errors that came in after its introduction in Java 8 and will incorporate more reliable support for subclassing, support for timeouts and delays, and a few utility methods.
The second point that deserves mentioning is the Stack Walking API. Java 9 will improve the way you traverse stack traces. This marks an official Java way to concoct stack traces, rather than simply treating them as plain text.
Stream API Improvements
Java 9 has included two distinct methods to interact with Streams such as takeWhile and dropWhile methods. Also, it has incorporated two overloaded methods like iterate and of nullable methods.
The two new methods dropWhile and takeWhile lets you get portions of a stream on the basis of a predicate.
- For instance, on an ordered stream, takeWhile renders the “longest prefix” of elements that are taken from the stream and matches the given predicate, starting at the commencement of the stream. On the other hand, the remaining items that were not matched by takeWhile are returned by dropWhile.
- On an un-ordered stream, starting at the inception of the stream, a subset of the stream’s elements that match the given predicate (but not all) is returned by takeWhile. dropWhile returns the rest of the stream elements after dropping subset of elements that match the given predicate.
InJava 9, Stream.ofNullable() method allows you to design a single-element stream that wraps a value if not null or is an empty stream otherwise. Stream.ofNullable() is quite similar to null condition check when the context of stream API is taken into consideration.
Process API Updates
Before Java 5, the only method to generate a new process was to use the Runtime.getRuntime().exec() method. When Java 5 came into existence ProcessBuilder API was added which supported a more accurate way of spawning new processes. Now, Java 9 is incorporating a new way of acquiring information about current and any spawned process.
To learn information on any process, now you should apply java.lang.ProcessHandle.Info interface. Few of the information programmers can now obtain from Process instance are as follows:
- Whether the process supports normal termination i.e. any of the “non-forcible” kill signals in Linux)
- The process ID (i.e. the “pid”)
- A handle to the current process
- A handle to the parent process
- A stream of handles to the direct children of the process
- A stream of handles to the descendants (direct children, their children, and so on recursively)
- A stream of handles to all processes visible to the current process
- Process metadata like the full command line, start instant, arguments, total CPU duration, and owning user.
To know about all the information of a newly spawned process, you can use process.toHandle() method to obtain ProcessHandle instance. Rest all of the things are as above
Additionally, you use ProcessHandle.allProcesses() to obtain a stream of ProcessHandle of all processes available in the system.
To obtain the list of all child processes, direct as well as n-level deep, you can make use of children() and descendants() method.
JShell – REPL Tool
A new command-line interactive tool, JShell is shipped with JDK 9 distribution (JEP 222) to assess statements, declarations, and expressions written in Java. JShell enables us to perform Java code snippets and get instantaneous results without having to build a solution or project.
Jshell is quite similar to what we have command window in linux OS (The Linux command line is a text interface to your computer, which allows users to execute commands). The only difference is that JShell is Java-specific. It has loads of other abilities, other than fulfilling simple code snippets like
- Launch inbuilt code editor in a new window
- Launch code editor of your choice in a separate window
- Perform code when Save operation takes place in these external editors
- Load pre-written classes from the file system
Platform and JVM Logging
JDK 9 has advanced logging in platform classes (JDK classes) and JVM components, with the help of a new logging API. It allows you to define a logging framework of your choice (for instance Log4J2) as a logging backend for logging messages from JDK classes. There are a few things you should learn about this API:
- The API is intended to be utilized by the classes in the JDK and not by application classes.
- For your application code, you will have to keep using other logging APIs.
- The API does not allow you to configure the logger programmatically.
The API comprises of the following:
- Java.lang.System.LoggerFinder, A service interface, which is an ideal static class
- Java.lang.System.Logger, An interface, which presents the logging API
- An overloaded process getLogger() in the java.lang.System class, which returns a logger instance.
JDK 9 also implemented a new command-line option, -Xlog , that provides you with one point of access to all messages logged from all classes of the JVM. The syntax to use the -Xlog option is as follows:
All the options are optional. If a previous part in -Xlog is missing, you have to use a colon for that part. Like, -Xlog::stderr symbolizes that all parts have defaulted, the output which is set as stderr.
HTTP/2 client in Java 9
Previously, developers often resorted to using third-party libraries, like Jersey, Apache HTTP, and others. Additionally, Java’s HTTP API predates the HTTP/1.1 specification, is synchronous, and difficult to manage. These limitations demanded a new API. The new HTTP client API implements the following:
- An easy and compact API to deal with most HTTP requests
- Support for HTTP/2 specification
- Better performance
- Better security
Multi-Release JAR files
Now, JAR files can include classes that have the capability only to run on the Java version they were compiled for. To use the latest features of the Java platform on the newer versions, the library developers will have to release a more current version of their library. Shortly, there will be various versions of the library being supported by the developers, which can be a nightmare. To surmount this shortcoming, these Java 9 features of multi-release JAR files empower developers to design JAR files with various versions of class files for several Java versions.
The Java Microbenchmark Harness (JMH) is advancing forward to the next step in its development and is teaming up with Java as an established benchmarking solution. Java Benchmarking Harness is used for designing, administering, and assessing nano/micro/milli/macro benchmarks.
There are a few factors to consider, like warm-up times and optimizations, which could possibly have a huge impact on results.
Java Microbenchmark Harness is the perfect option if you are after the most reliable results to help you obtain the correct decision after your benchmarks.
So, these were all about Java 9 and new Java 9 features. There are various useful features that got dropped from Java 9. However, most of those features got implemented in Java 10.
A more light-weighted and standardized JSON API is talked about by many java developers. Nevertheless, it didn’t get implemented due to funding issues.
Mentioned below here are a few other features of Java 9 as well
- Garbage Collector(GC) Improvements
- Filter Incoming Serialization Data
- Deprecate the Applet API
- Indify String Concatenation
- Improved Method Handles
- Compact Strings
- Parser API for Nashorn
- What are the main goals of Java 9?
Answer: The chief goals for Java 9 are to:
- Create the Java Standard Edition platform, and the JDK extra navigable to scale down for small computing devices.
- Improvement of the overall security and maintenance not only of the JDK but the Java Implementations in general.
- Make it simpler for Java developers to develop and support the code libraries and larger applications, for both the Java SE and EE Platforms
- What is Process API in Java 9?
Answer: In Java 9, Process API is capable of managing and controlling operating system processes which have been improved considerably. ProcessHandle Class now grants process’s native process ID, accumulated CPU time, start time, command, arguments, user, parent process, and descendants.
- Which method is added to map in Java9?
Answer: of() was added, which is a convenient way to generate instances of Map interface.It has the ability up to 10 key-value pairs.
- What is the difference between Java 8 and Java 9?
Answer: Java 8 and Java 9 are two separate versions that come under the umbrella of Java programming language, where Java 9 supports scripting language along with object-oriented programming language. Java 8 is equipped with Java Time API and Java IO improvements, whereas Java 9 comes with has Money and Currency API updates.