Quick preview of new features in Java 9

Source: Internet
Author: User
Tags http 2

Original Source: Wangwenjun69

Java 8 has been out for more than three years, originally planned July 2016 release Java 9, but for various reasons, Java 9 was postponed to 2017 years of March, I also see the open JDK on the official web site Java 10 standards are also in the making, Java development is really getting faster, before the release of Java 9, we can use its snapshot version, first to experience what new Java 9 features, the following list comes from the official documents, looks like a lot, but really subversive is actually the module System, the rest of the main is a number of new feature additions, there are some features of the strengthening, in this article, we will introduce the main several, will not go to say, the data is not much, so I would like to say that the other Java 8 is I think so far the biggest change in Java, Not only is the feature increase, more is the change of the programming style, if you have not mastered Java 8, suggest you look at my recorded teaching video, roughly 40 episodes, specifically for the Java 8 features of the actual combat video, for:


102:process API updates110:http 2 client143:improve contended locking158:unified JVM logging165:compiler Control193: Variable handles197:segmented Code cache199:smart Java compilation, Phase two200:the Modular jdk201:modular Source Cod E211:elide deprecation Warnings on Import statements212:resolve Lint and doclint warnings213:milling Project coin214:r Emove GC combinations Deprecated in JDK 8215:tiered attribution forJavac216:process Import Statements correctly217:annotations Pipeline 2.0219:datagram Transport Layer Security (DTLS) 220 : Modular run-time images221:simplified Doclet API222:jshell:The Java Shell (read-eval-print Loop) 223:new Version-stri Ng SCHEME224:HTML5 Javadoc225:javadoc search226:utf-8 Property files227:unicode 7.0228:add more Diagnostic Commands22 9:create PKCS12 keystores by Default231:remove launch-time JRE Version selection232:improve Secure application Performa Nce233:generate run-time Compiler Tests automatically235:test class-file Attributes Generated by Javac236:parser API forNashorn237:linux/aarch64 port238:multi-release JAR files240:remove the JVM TI hprof agent241:remove the jhat Tool243: Java-level JVM Compiler interface244:tls application-layer Protocol negotiation extension245:validate JVM Command-Line F Lag Arguments246:leverage CPU Instructions forGHash and Rsa247:compile forOlder Platform Versions248:make G1 the Default garbage collector249:ocsp stapling forTls250:store interned Strings in CDS archives251:multi-resolution images252:use CLDR Locale Data by Default253:prepare JavaFX UI Controls & CSS APIs forModularization254:compact strings255:merge Selected Xerces 2.11.0 Updates into Jaxp256:beaninfo annotations257:update Javafx/media to newer Version of Gstreamer258:harfbuzz font-layout engine259:stack-walking api260:encapsulate most Inte Rnal apis261:module System262:tiff Image i/o263:hidpi Graphics on Windows and Linux264:platform Logging API and Servic E265:marlin Graphics renderer266:more Concurrency updates267:unicode 8.0268:xml catalogs269:convenience Factory Metho Ds forcollections270:reserved Stack Areas forCritical sections271:unified GC logging272:platform-specific Desktop features273:drbg-based securerandom implementations274:enhanced Method handles275:modular Java application packaging276:dynamic Linking of Language-Define D Object models277:enhanced deprecation278:additional Tests forHumongous Objects in G1279:improve test-failure troubleshooting280:indify String concatenation281:hotspot C + + Unit-Test  Framework282:jlink:The Java linker283:enable GTK 3 on linux284:new HotSpot Build system285:spin-wait hints287:sha-3 Hash algorithms288:disable SHA-1 certificates289:deprecate the Applet api290:filter Incoming serialization Data292:im Plement Selected ECMAScript 6 Features in nashorn294:linux/s390x port295:ahead-of-time compilation
1. Modular System–jigsaw Project

This feature is the largest Java 9 feature, Java 9 was originally named Jigsaw, recently changed to Modularity,modularity provides a similar to the OSGi framework of the functionality, there is a mutual dependency between the modules, you can export a common API, and hide the implementation details, Java provides the main motive of this function is to reduce the memory overhead, we all know that at the time of the JVM startup, there will be at least 30~60MB memory load, The main reason is that the JVM needs to load the Rt.jar, regardless of whether the class is ClassLoader loaded, the first step of the entire jar will be loaded into memory by the JVM, the module can be loaded according to the needs of the module to run the required class, then how the JVM knows the need to load those classes? This is a new file introduced in Java 9 Module.java We take a look at an example (Module-info.java)

  1 module Com.baeldung.java9.modules.car {  2     requires Com.baeldung.java9.modules.engines;   3     exports com.baeldung.java9.modules.car.handling;   4 }

For more information on programming Java 9 modules, please refer to a book: "Java 9 modularity" in more detail, describes the current Java on the management of the jar since the chaos, the introduction of modularity after the change will be very obvious difference.

2. A New Http Client

For the time being, the HTTP access functionality provided by the JDK is almost always dependent on httpurlconnection, but this class is seldom used when writing code, and we will typically choose Apache's HTTP Client, which is in Java A new package:java.net.http was introduced in version 9, which provides good support for HTTP access, supports not only Http1.1 but also HTTP2, and WebSocket, which is said to exceed Apache HttpClient , Netty,jetty, simply look at a snippet of code

  1new URI ("http://www.94jiankang.com");   2 HttpRequest request = Httprequest.create (Httpuri). GET ();   3 httpresponse response = Request.response ();   4 String responsebody = Response.body (httpresponse.asstring ());
3. Process API Enhance

In a very early version of Java, an API such as process is available to get some information about the processes, including runtime, and even some of the commands used to execute the current host, but let's consider a question, how do you get the PID of your current Java runtime program? Obviously through the process is not available, need to rely on JMX to get, but in this enhancement, you will be very easy to get this information, we look at a simple example

  1 processhandle self = processhandle.current ();   2long PID = Self.getpid ();   3 processhandle.info procinfo = Self.info ();   4  5 optional<string[]> args = procinfo.arguments ();   6 optional<string> cmd =  procinfo.commandline ();   7 optional<instant> startTime = Procinfo.startinstant ();   8 optional<duration> cpuusage = Procinfo.totalcpuduration ();

There are a lot of optional, this is the Java 8 API, also in Java 9 to enhance it, I in the Java 8 Combat video on the optional API source-level analysis, interested must go to see.

We have obtained the process of the JVM, how do we gracefully stop the process? The following code gives the answer

  1 childproc = Processhandle.current (). Children ();   2 childproc.foreach (prochandle, {  3     asserttrue ("" + prochandle.getpid ( ), Prochandle.destroy ());   4 });

Through a small piece of code above, we also found that Java 9 also added some enhancements to the assertion mechanism, say a few more digression, our current system running a heavily dependent on the Hive Beelineserver program, Beeline server is not very stable, often appear stuttering, Even suspended animation, false after death also do not reply to the problem, so that our program will also appear to lag, if the operation and maintenance personnel do not clean up, the system runs a few months after the discovery of a lot of zombie process, so add a get the current JVM PID function, and then judge to more than a given time to kill it actively, It's all about the behavior inside the program, but getting the PID has to be done with JMX, and the command to kill it also has to rely on the operating system, such as Kill, which is a lot of trouble, but the Java 9 approach is noticeably more elegant and convenient.

4. Changes in Try-with-resources

As we all know, try-with-resources is an important feature introduced from JDK 7, as long as the interface inherits Closable can use Try-with-resources, reduce the writing of the finally statement block, in Java 9 will be more convenient for this feature

  1new myautocloseable ();   2try (Mac) {  3     //Do some stuff with Mac    4 }   5  6try (new myautocloseable () {}. finalwrapper.finalcloseable) {  7    //Do some stuff with finalcloseable     8 Catch (Exception ex) { }

Our closeable does not have to be written in try () at all.

5. Diamond Operator Extension
  1new//anonymous inner class    2 };   3  4extendsnew fooclass<> (1) {  5     // Anonymous inner class    6 };   7  8new//anonymous inner class    9 };
6. Interface Private Method
1 InterfaceInterfacewithprivatemethods {2 3     Private StaticString Staticprivate () {4         return"Static Private";5}6 7     PrivateString Instanceprivate () {8         return"Instance Private";9}Ten  One     default voidCheck () { AString result = Staticprivate (); -Interfacewithprivatemethods pvt =NewInterfacewithprivatemethods () { -             //Anonymous class the}; -result = Pvt.instanceprivate (); -} -}}

This feature is purely for the default method and static method services in Java 8.

7. Jshell Command Line Tool

When the Java 8 came out, a lot of people shouted, this is to Rob Scala and other based on the JVM Dynamic language market Ah, some of them gave a Java do not go to the direction, that is Scala can be used as a scripting language, Java can? Obviously before this Java, TA also does not have the dynamic, but this Java 9 let Java can also be like scripting language to run, mainly thanks to Jshell, we look at this demo

  1 jdk-9\bin>jshell.exe  2 |  Welcome to Jshell--Version 9  3 |  For a introduction type:/help Intro  4 jshell> "This ismy long string. I want apart of it ". substring (8,19);   5 $ ==> "my long string"

This is what we run under the Jshell console, how do we run the script file?

  1 jshell>/save c:\develop\JShell_hello_world.txt  2 jshell>/open C:\develop\JShell _hello_world.txt  3 Hello jshell!
8.JCMD Sub-commands

Remember in Java 8, jhat This command, but soon added some new commands in Java 9, such as the jcmd we are going to introduce, with which you can see very well the dependencies between the classes

1Jdk-9\bin>jcmd 14056 Vm.class_hierarchy-i-S Java.net.Socket214056:3java.lang.object/NULL4|--java.net.socket/NULL5|Implementsjava.io.closeable/NULL(declared intf)6|Implementsjava.lang.autocloseable/NULL(Inherited intf)7| |--org.eclipse.ecf.internal.provider.filetransfer.httpclient4.closemonitoringsocket8| |Implementsjava.lang.autocloseable/NULL(Inherited intf)9| |Implementsjava.io.closeable/NULL(Inherited intf)Ten| |--javax.net.ssl.sslsocket/NULL One| |Implementsjava.lang.autocloseable/NULL(Inherited intf) A| |Implementsjava.io.closeable/NULL(Inherited intf)
9.мulti-resolution Image API

Interface Java.awt.image.MultiResolutionImage encapsulates a series of different resolution images to a single object API, I can get resolution-specific based on a given DPI matrix, take a look at the following code snippet

  1 bufferedimage[] resolutionvariants = ....   2 multiresolutionimage bmrimage  3   new basemultiresolutionimage (BaseIndex, resolutionvariants);   4 Image testrvimage = bmrimage.getresolutionvariant (16, 16);   5 assertsame ("Images shouldbe the same", Testrvimage, resolutionvariants[3]);

About AWT things, I hardly contact, if useful to friends, such as JDK 9 come out, I feel the use of it.

Ten. Variable Handles

Long ago Rumors that Java will be unsafe this class screen out, not for everyone to use, this time to see his official documents, it seems that all the packages that have sun start will not be used in application, but Java 9 provides a new API for everyone to use.

A new package is provided in JDK 9, called Java.lang.invoke, which has a number of important analogies such as Varhandler and Methodhandles, which provide functionality similar to atomic operations and unsafe operations.

11.publish-subscribe Framework

The framework for message publishing subscriptions is provided in the new version of JDK 9, which is primarily provided by the flow class, which also appears in Java.util.concurrent and provides reactive programming patterns.

Unified JVM Logging

This feature introduces a common logging system for all the components of the JVM, providing the infrastructure for the JVM logs, and you can use only a uniform log instruction, instead of adding special tags specifically for printing some logs, such as:

  1 java-xlog:gc=debug:file=gc.txt:none ...   2 jcmd 9615 VM.log output=gc_logs WHAT=GC
Immutable Set

In fact, in earlier versions of Java already have such a function, such as collections.xxx can be a collection package as immutable, but this version of Java 9 added to the corresponding set and list, And there is a special new package for these specific implementation java.util.ImmutableCollections, a feature that is really the same as Scala.

  1 set<string> strkeyset = Set.of ("key1", "key2", "Key3");
Optional to Stream

To option provides the stream function, about the use of optional, I told in my tutorial very detailed, if you have not mastered, hold on.

  1 list<string> filteredlist = Listofoptionals.stream ()  2   . FlatMap (Optional:: Stream)  3   
15. Other
    1. General characteristics I introduce so much, you can also go to openjdk official website Download snapshot version of Java 9来 Play, of course, there are many other features I will not introduce, here is just about the mention
    2. Lightweight JSON text-processing API
    3. Remove many GCC recyclers that have been expired (remove Oh, because only expired tags are added in jdk 8)
    4. Use the G1 garbage collector as the default garbage collector
    5. HTML5-style Java doc
    6. Java doc is just a smart search feature
    7. The JavaScript engine has been further upgraded.
    8. The hash algorithm of SHA-3 is introduced.
    9. The Great God Doug Lea continues to serve this version of the JDK and will amaze everyone.

Quick preview of new features in Java 9

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.