Summary of new features for Java9

102: Process API Updates
110: HTTP 2 Client
143: Improve Contended Locking
158: Unified JVM Logging
165: Compiler Control
193: Variable Handles
197: Segmented Code Cache
199: Smart Java Compilation, Phase Two
200: The Modular JDK
201: Modular Source Code
211: Elide Deprecation Warnings on Import Statements
212: Resolve Lint and Doclint Warnings
213: Milling Project Coin
214: Remove GC Combinations Deprecated in JDK 8
215: Tiered Attribution forJavac 216: Process Import Statements Correctly 217: Annotations Pipeline 2.0 219: Datagram Transport Layer Security (DTLS) 220: Modular Run-Time Images 221: Simplified Doclet API 222: jshell: The Java Shell (Read-Eval-Print Loop) 223: New Version-String Scheme 224: HTML5 Javadoc 225: Javadoc Search 226: Utf-8 Property Files 227: Unicode 7.0 228: Add More Commands 229: Create PKCS12 Keystores by Default 231: utF-8 Property Files 227: Unicode 7.0 228: Add More Commands 229: Create PKCS12 Keystores by Default 231: Remove Launch-Time JRE Version Selection 232: Improve Secure Application Performance 233: Generate Run-Time Compiler Tests Automatically 235: Test Class-File Attributes Generated by javac 236: Parser APIfor Nashorn
237: Linux/AArch64 Port
238: Multi-Release JAR Files
240: Remove the JVM TI hprof Agent
241: Remove the jhat Tool
243: Java-Level JVM Compiler Interface
244: TLS Application-Layer Protocol Negotiation Extension
245: Validate JVM Command-Line Flag Arguments
246: Leverage CPU Instructions for GHASH and RSA
247: Compile for Older Platform Versions
248: Make G1 the Default Garbage Collector
249: OCSP Stapling for TLS
250: Store Interned Strings in CDS Archives
251: Multi-Resolution Images
252: Use CLDR Locale Data by Default
253: Prepare JavaFX UI Controls & CSS APIs for Modularization
254: Compact Strings
255: Merge Selected Xerces 2.11.0 Updates into JAXP
256: BeanInfo Annotations
257: Update JavaFX/Media to Newer Version of GStreamer
258: HarfBuzz Font-Layout Engine
259: Stack-Walking API
260: Encapsulate Most Internal APIs
261: Module System
262: TIFF Image I/O
263: HiDPI Graphics on Windows and Linux
264: Platform Logging API and Service
265: Marlin Graphics Renderer
266: More Concurrency Updates
267: Unicode 8.0
268: XML Catalogs
269: Convenience Factory Methods for Collections
270: Reserved Stack Areas for Critical Sections
271: Unified GC Logging
272: Platform-Specific Desktop Features
273: DRBG-Based SecureRandom Implementations
274: Enhanced Method Handles
275: Modular Java Application Packaging
276: Dynamic Linking of Language-Defined Object Models
277: Enhanced Deprecation
278: Additional Tests for Humongous Objects in G1
279: Improve Test-Failure Troubleshooting
280: Indify String Concatenation
281: HotSpot C++ Unit-Test Framework
282: jlink: The Java Linker
283: Enable GTK 3 on Linux
284: New HotSpot Build System
285: Spin-Wait Hints
287: SHA-3 Hash Algorithms
288: Disable SHA-1 Certificates
289: Deprecate the Applet API
290: Filter Incoming Serialization Data
291: Deprecate the Concurrent Mark Sweep (CMS) Garbage Collector
292: Implement Selected ECMAScript 6 Features in Nashorn
294: Linux/s390x Port
295: Ahead-of-Time Compilation
297: Unified arm32/arm64 Port
298: Remove Demos and Samples
299: Reorganize DocumentationCopy the code

New features in java9

  • Modular system

Modularity is a very general concept. In software, modularity can be applied to writing and implementing a program and computing system as independent modules, rather than as a single and complete design.

The main change in Java 9 is the modular system that has been implemented. The introduction of modularity makes the JDK usable on smaller devices. Applications using modular systems require only a few JDK modules for those applications, not the entire JDK framework. Modular systems can also encapsulate common classes into a module. Therefore, a class defined as public wrapped in a module cannot be used anywhere else unless the module explicitly defines the module. Due to this change in Java 9, internal Java apis (such as com.sun.*) are not available by default.

All modules will need to be described in the module-ionfo. Java file, which is at the top of the Java code structure.

module me.aboullaite.java9.modules.car { requires me.aboullaite.java9.modules.engines; / / dependent module exports me. Aboullaite. Java9. Modules. Car. Handling; // Package exported in module}Copy the code

Our module car relies on the + module engine and needs to export the handling package.

See the OpenJDK project Jigsaw: A Quick Start to Modular Systems for more examples

  • Java JShell – 9 REPL

REPL is a command line tool for quickly running statements.

In Java, if you want to execute a simple statement, we either create a class with a main method or a Test class that can execute. This may not seem so useful if you want to execute certain statements and see the results immediately when you are starting a Java program. (More like Python running a program from the command line…)

JShell tries to solve this problem. Java developers can use JShell to declare variables, evaluate expressions, and execute statements without creating classes. JShell can also load statements from or save statements to files. And JShell can also be TAB key auto-completion feature.

  • Set factory method

Before 9 Java, Java can only use a few practical methods (for example: the Collections. UnmodifiableCollection (Collection <? Extends T> c)) creates a collection of views that cannot be modified. For example, we could create an unmodifiable view of a Collection in Java 8 using a statement like the following. This is the easiest way to create it, but it looks terrible! Isn’t it?

 Map<String,String> immutableMap = 
      Collections.unmodifiableMap(
         new HashMap<String,String>(){
           {
           put("key1"."value1");
           put("key2"."value2");
           put("key3"."value3"); }});Copy the code

Java9 introduced some useful factory methods for creating immutable collections:

Map<String,String> immutableMap = Map.of("key1"."value1"."key2"."value2"."key3"."value3");Copy the code

Examples of factory methods are as follows:

EmptyImmutableList = list.of (); emptyImmutableList = list.of (); Set<String> emptyImmutableSet = Set.of(); Map emptyImmutableMap = Map.of(); List<String> immutableList = list.of ("one"."two");
Set<String> immutableSet = Set.of("value1"."value2");
Map<String,String> immutableMap = Map.of("key1"."value1"."key2"."value2"."key3"."value3");Copy the code
  • Private methods in the interface

The Java 8 interface introduces both default and static methods. Although Java 8 was first planned to implement private methods of interfaces, it was implemented in Java 9. The default and static methods can share private methods in the interface, thus avoiding code redundancy and making the code cleaner. If a private method is static, it belongs to the interface. And there are no static private methods that can only be called by instances in the interface.

interface InterfaceWithPrivateMethods{
    private static String staticPrivate() {return "static private";
    }

    private String instancePrivate() {return "instance private";
    }

    default void check(){
        String result = staticPrivate();

        InterfaceWithPrivateMethods p = new InterfaceWithPrivateMethods(){// anonymous class}; result = p.instancePrivate(); }}Copy the code
  • Reactive flow

The Flow API in JDK9 corresponds to the reactive Flow specification, which is a de facto standard. JEP 266 contains a minimal set of interfaces that can capture core asynchronous publishing and subscription.

Java. Util. Concurrent. Flow consists of the following four interface:

Flow.Processor

Flow.Publisher

Flow.Subscriber

Flow.Subscription manager

All of these interfaces support a reactive stream publish-subscribe framework. Java 9 also provides the utility class SubmissionPublisher. A publisher produces one or more items that are consumed by one or more consumers. And subscribers are managed by the subscription manager. The subscription manager connects publishers and subscribers.

  • Multiresolution image API – JEP 251

The goal is to define a multi-resolution graphics API so that developers can easily manipulate and display images in different resolutions. The new API is defined in the java.awt.image package. This API helps us with the following:

  1. Encapsulate images of different resolutions into one (multi-resolution) image as a variant of this.

  2. Gets all variations of this image.

  3. Get image variant of a specific resolution – represents a logical image of a given size with a known resolution unit of DPI, and this image is the best variant.

Based on the current screen resolution size and the image conversion algorithm applied, the java.awt.Graphics class can get the required variations from the interface MultiResolutionImage. Java awt. Image. AbstractMultiResolutionImage class provides a Java awt. Image. AbstractMultiResolutionImage default implementation. AbstractMultiResolutionImage implementation is the basis of Java. The awt. Image. BaseMultiResolutionImage.

  • Process API improvements

Apis have been added to control and manage operating system processes. In Java9, code is expected to fetch LINUX pids

Methods in previous versions:

public static void main(String[] args) throws Exception{
    Process proc = Runtime.getRuntime().exec(new String[]{"/bin/sh"."-c"."echo $PPID"});

    if(proc.waitFor() == 0){
        InputStream in = proc.getInputStream();
        int available = in.available();
        byte[] outputBytes = new byte[available];

        in.read(outputBytes);
        String pid = new String(outputBytes);

        System.out.println("Your PID is:"+pid); }}Copy the code

In Java9, this is changed to the following (also supported on all operating systems) :

System.out.println("Your PID is:" + Process.getCurrentPid());Copy the code
  • Exception handling

In Java 7, the try-with-resouces syntax requires that a new variable be declared for each resource that is managed by the try-with-Resources statement.

In Java 9: If a resource is referenced by a final variable or its equivalent, try-with-Resources can manage the resource without declaring a new variable.

MyAutoCloseable mac = new MyAutoCloseable();

try(mac){

//do some stuff with mac

}

try(new MyAutoCloseable(){}.finalWrapper.finalCloseable){

//do some stuff with finalCloseable

}

  • An extension of the diamond operator’s scope

The diamond operator given in Java 7 makes writing code much easier. In the example below, you can see that the List is more readable in Java 7, but the diamond operator was not allowed on anonymous classes in Java 7, but Java 9 has improved the situation by allowing the diamond operator on anonymous classes. The following example only compiles in Java 9.

List<String> list = new ArrayList<>(){};Copy the code
  • Enhanced comments are Deprecated

The @deprecated annotation marks the Java API. The @deprecated annotation has a variety of meanings. For example, it can indicate that at some point in the near future, the marked API will be removed. It can also indicate that the API is broken and should not be used again. It has many other meanings. To provide more information about @deprecated, @Deprecated adds the forRemoval element and the since element.

A tool for scanning JAR files, JdeprScan, is also available in Java SE 9. The tool can also scan an aggregation class that uses deprecated API elements in Java SE. This tool will help applications that use a compiled library, so that users are unaware of the deprecated apis used in the compiled library.

  • Unified JVM logging

It is difficult to know the root cause of JVM performance problems and crashes. One solution to this problem is to introduce a single system for all JVM components that support fine-grained and easily configurable JVM logging. Currently, different JVM components use different mechanisms and rules for logging, making it difficult for JVMS to debug.

  • Comment @safevarargs extension of scope

Until Java 8, @Safevarargs could not be used on static methods, final methods, and constructors. But these methods or constructors cannot be overridden. One of these methods is missing another method that cannot be overridden: a private method. Java 9 can add @Safevarargs to private methods. The following example is correct in Java 9, but throws a compile-time error in Java 8: the @Safevarargs annotation cannot be used on a non-final instance method, iAmSafeVaragrsMethod.

@SafeVarargs
private void iAmSafeVaragrsMethod(String... varagrgs){
    for(String each : varagrgs){ System.out.println(each); }}Copy the code
  • HTTP 2 client

Java 9 features a new HTTP client API that supports both the HTTP/2 and WebSocket protocols and replaces the legacy HTTPURLConnectionAPI. These changes should not be made in Java 9. These apis are available from the Incubator module. So by default, the module is not available by classpath, and you need to configure the module using the –add-modules command option to add the module to the classpath.

Create an HTTP Request Request and get an asynchronous response:

URI testPageURI = new URI("http://127.0.0.1:8080/testPage");
CompletableFuture<HttpResponse> nonBlockingResponse = HttpRequest
        .create(testPageURI)
        .GET().responseAsync();

int tries = 0;
while(! nonBlockingResponse.isDone() && tries++ < 5){ Thread.sleep(5); }if(nonBlockingResponse.isDone()){
    HttpResponse response = nonBlockingResponse.get();
    System.out.println("Satus code."+response.statusCode()+"-- >"+response.body(HttpResponse.asString()));
}else{
    nonBlockingResponse.cancel(true);
    System.out.println("cancelling,could not get response");
}Copy the code
  • HTML5 style Java help documentation

Java 8 and previous versions generate Java help documentation in HTML 4, which has been a standard for a long time. In Java 9, an output option was added to the options section of the Javadoc command line with either HTML 4 or HTML 5. HTML 4 is now the default output markup language, but HTML 5 will be the default output markup language in future JDK releases. The Java help document is still composed of three frameworks, which will not change, and the Java help document output in HTML 5 will remain the same structure.

  • Other features
1. Retain the underscore character. Variables cannot be named _; 2. Discard the Applet API. 3. Javac no longer supports Java1.4 and earlier versions. 4. Deprecate the Java browser plug-in; 5. Stack traversal API - The stack traversal API filters and delays access to information in the stack trace.Copy the code

More official documentation for JDK9