编程知识 cdmana.com

This article takes you through the important new features of jdk9 ~ 14!

Java9

Published on 2017 year 9 month 21 Japan . As Java8 after 3 The new version was released in half a year ,Java 9 belt There have been many major changes, the most important of which is Java Introduction of platform module system , Others, such as assembly 、Stream flow

Java Platform module system

Java Platform module system , That is to say Project Jigsaw, Modular development practices are introduced to Java In the platform . After introducing the modular system ,JDK Be reorganized into 94 A module .Java Applications can be added through jlink Tools , Create only the dependent JDK Module's custom runtime image . This can greatly reduce Java The size of the runtime environment .

Java 9 The most important feature of the module is that its workpieces (artifact) The root directory of contains a description of the module module-info.class writing Pieces of . The format of the artifact can be traditional JAR Documents or Java 9 Newly added JMOD file .

Jshell

jshell yes Java 9 A new utility . by Java Similar to Python Real time command line interaction tool .

stay Jshell You can directly enter an expression and view its execution result

aggregate 、Stream and Optional

  • increase 了  List.of()Set.of()Map.of()  and  Map.ofEntries() Wait for factory methods to create immutable sets , such as List.of("Java", "C++");Map.of("Java", 1, "C++", 2);( This part has some reference Guava The smell of )
  • Stream  New method added in  ofNullabledropWhiletakeWhile  and  iterate  Method .Collectors  New method added in  filtering  and  flatMapping
  • Optional  Class  ifPresentOrElseor  and  stream  Other methods

process API

Java 9 Added  ProcessHandle  Interface , Native processes can be managed , Especially suitable for managing long-running processes

Platform log API And the service

Java 9 Allow for JDK The same log implementation as the application configuration . Added  System.LoggerFinder  Used to manage JDK send Using the log recorder to achieve .JVM At runtime there is only one system wide  LoggerFinder  example .

We can add our own  System.LoggerFinder  To achieve JDK And application use SLF4J Wait for other logging frameworks .

Reactive flow ( Reactive Streams )

  • stay Java9 Medium  java.util.concurrent.Flow  The core interface of reactive flow specification is added in class
  • Flow It contains  Flow.PublisherFlow.SubscriberFlow.Subscription  and  Flow.Processor  etc. 4 Core interfaces .Java 9 It also provides SubmissionPublisher  As Flow.Publisher  An implementation of .

Variable handle

  • A variable handle is a reference to a variable or group of variables , Include static fields , Non static domain , Array elements and components of off heap data structures
  • The meaning of the variable handle is similar to the existing method handle MethodHandle
  • from Java class java.lang.invoke.VarHandle  To express , You can use classes  java.lang.invoke.MethodHandles.Lookup  Static factory method to create  VarHandle  Yes like

Improved method handle (Method Handle)

  • Method handle from Java7 Start introducing ,Java9 In the class java.lang.invoke.MethodHandles  More static methods are added to create different types of method handles

Other new features

  • Interface private methods  :Java 9 Allow private methods in interfaces
  • try-with-resources enhance  : stay try-with-resources You can use effectively-final Variable ( What is? effectively-final Variable , See this article  http://ilkinulas.github.io/programming/java/2016/03/27/effectively-final-java.html
  • class  CompletableFuture  Several new methods have been added (completeAsync ,orTimeout  etc. )
  • Nashorn Engine enhancements  :Nashorn from Java8 Introduced JavaScript engine ,Java9 Yes Nashorn Made some enhancements , Achieved some ES6 New features
  • I/O New features of flow  : New methods have been added to read and copy InputStream Data contained in
  • Improve application security  :Java 9 Added 4 individual SHA- 3 The hash algorithm ,SHA3-224、SHA3-256、SHA3-384 and S HA3-512

Java10

Published on 2018 year 3 month 20 Japan , The most famous feature should be var keyword ( Local variable type inference ) The introduction of , There are other garbage collector improvements 、GC improvement 、 Performance improvement 、 Thread control and other new features

var keyword

  • Introduce  : Provides var Keywords declare local variables :var list = new ArrayList<String>(); // ArrayList<String>
  • limitations  : Can only be used for local variables with constructors and for In circulation

Guide Brother : actually Lombok A similar keyword has long been used , Use it to simplify the code , But it may reduce the readability of the program 、 Maintainability . In general , I personally do not recommend the use of .

Immutable set

list,set,map Provides a static method copyOf() Returns an immutable copy of the input parameter set ( The following is a JDK Source code )

static <E> List<E> copyOf(Collection<? extends E> coll) { return ImmutableCollections.listCopy(coll);
}

java.util.stream.Collectors Static methods are added in , Used to collect elements in a stream as immutable sets

Optional

  • Added orElseThrow() Method to throw an exception when there is no value

Parallel full garbage collector G1

from Java9 Start G1 The default garbage collector ,G1 It's designed as a low latency garbage collector , To avoid Full GC, however Java9 Of G1 Of FullGC It still uses single thread to complete the mark clearing algorithm , This may cause the garbage collection period to trigger when memory cannot be recycled Full GC.

In order to minimize Full GC The impact of application pauses , from Java10 Start ,G1 Of FullGC Change to a parallel tag removal algorithm , At the same time, the same number of parallel worker threads will be used as the young generation recycling and hybrid recycling , This reduces Full GC Happen , For better performance improvement 、 More throughput .

Application class data sharing

stay Java 5 Class data sharing mechanism has been introduced in (Class Data Sharing, abbreviation CDS), Allows a set of classes to be preprocessed as shared Archives , So that memory mapping can be done at run time to reduce Java The start time of the program , When more than one Java virtual machine (JVM) When sharing the same archive , It can also reduce the dynamic memory usage , At the same time, reduce the resource consumption when multiple virtual machines run on the same physical or virtual machine

Java 10 In the existing CDS On the basis of function, expand again , To allow application classes to be placed in a shared archive .CDS Characteristics in the original bootstrap Class based , The extension adds the CDS (Application Class-Data Sharing) Support . The principle is : Record the process of loading the class at startup , Write to text file , Read the startup text directly and load . Imagine if the application environment doesn't change much , Start up speed will be improved

Other features

  • Threads - Local control :Java 10 Introduction of thread control in JVM The concept of safety point , Will allow global... To be run without JVM In the case of security point, thread callback , By the thread itself or JVM Thread to execute , At the same time, keep the thread blocked , This makes it possible to stop a single thread , Instead of just enabling or stopping all threads
  • Heap allocation on standby storage :Java 10 Will make JVM The ability to use heaps for different types of storage mechanisms , Heap memory allocation on optional memory devices
  • Unified garbage collection interface :Java 10 in ,hotspot/gc Code implementation , Introduce a clean GC Interface , Improvement is different GC Isolation of source code , Multiple GC The implementation detail code shared between should exist in the helper class . The main reason for unifying the garbage collection interface is : Let the garbage collector (GC) This part of the code is cleaner , Easy for new people to develop , It is convenient for subsequent troubleshooting .

Java11

Java11 On 2018 year 9 month 25 Official release , This is an important version !Java 11 and 2017 year 9 Released in April Java 9 as well as 2018 year 3 Released in April Java 10 comparison , The biggest difference is : In the long run support (Long-Term-Support) aspect ,Oracle Say yes to Java 11 Provide strong support , This support will last until 2026 year 9 month . This is the evidence Java 8 First long-term version supported later .

String reinforcement

Java 11 A series of string processing methods are added , As shown below .

Guide Brother : White dots are more layers of encapsulation ,JDK The people in the development team have seen the common tool framework on the market !

// Determines if the string is empty
" ".isBlank();//true // Remove the leading and trailing spaces from the string
" Java ".strip();// "Java" // Remove the first space of the string
" Java ".stripLeading(); // "Java " // Remove the space at the end of the string
" Java ".stripTrailing(); // " Java" // How many times do I repeat a string
"Java".repeat(3); // "JavaJavaJava" // Returns a set of strings separated by line terminators .
"AnBnC".lines().count(); // 3
"AnBnC".lines().collect(Collectors.toList());

ZGC: Scalable low latency garbage collector

ZGC namely Z Garbage Collector, It's a scalable 、 Low latency garbage collector .

ZGC It is mainly designed to meet the following objectives :

  • GC The pause time shall not exceed 10ms
  • Can handle hundreds of MB A small pile of , Can also handle a few TB A lot of
  • Application throughput will not drop more than 15%( And G1 Recycling algorithm compared to )
  • It is convenient to introduce new GC Characteristics and utilization colord
  • Needles and Load barriers Optimization lays the foundation
  • Currently only supported Linux/x64 Bit platform

ZGC at present   In the experimental stage , Only support Linux/x64 platform

standard HTTP Client upgrade

Java 11 Yes Java 9 Introduced in and in Java 10 Updated in Http Client API Standardized , Incubating in the first two versions at the same time ,Http Client Almost completely rewritten , And now fully supports asynchronous non blocking .

also ,Java11 in ,Http Client The name of the bag is  jdk.incubator.http  Change it to java.net.http, The API adopt  CompleteableFuture  Provide non blocking request and response semantics .

It's easy to use , as follows :

var request = HttpRequest.newBuilder()

.uri(URI.create("https://javastack.cn"))  

.GET()  

.build();  

var client = HttpClient.newHttpClient(); // Sync
HttpResponse<String> response = client.send(request, HttpResponse.BodyHandlers.ofString());

System.out.println(response.body()); // asynchronous
client.sendAsync(request, HttpResponse.BodyHandlers.ofString())

.thenApply(HttpResponse::body)  

.thenAccept(System.out::println); 

Simplify the way to start a single source file

  • Enhanced Java starter , To enable it to run a single file Java Source code . This feature allows the use of Java The interpreter directly executes Java Source code . Source code compiled in memory , The interpreter then performs . The only constraint is that all related classes must be defined in the same Java In file
  • about Java Beginners and people who want to try simple programs are particularly useful , And can be with jshell Use it together
  • It can enhance the use of Java The ability to write scripts

be used for Lambda Local variable syntax for parameters

  • from Java 10 Start , The key feature of local variable type inference is introduced . Type inference allows keywords var As a type of local variable rather than an actual type , The compiler infers the type from the value assigned to the variable
  • Java 10 Chinese vs var There are several restrictions on keywords

    • Can only be used on local variables
    • Must be initialized when declaring
    • Cannot be used as a method parameter
    • Can't be in Lambda Use in expressions
  • Java11 Start to allow developers in Lambda Use in expressions var Make parameter declaration

Other features

  • New garbage collector Epsilon, A completely negative GC Realization , Allocate limited memory resources , Minimize memory usage and memory throughput latency
  • Low overhead Heap Profiling:Java 11 Provides a low overhead Java Heap allocation sampling method , Can get heap allocation Java Object information , And can pass through JVMTI Access heap information
  • TLS1.3 agreement :Java 11 Transport layer security is included (TLS)1.3 standard (RFC 8446) The implementation of the , Replaced the TLS, Include TLS 1.2, At the same time, it also improved other TLS function , for example OCSP Binding extension (RFC 6066,RFC 6961), And session hashing and extended master key extension (RFC 7627), There are also many improvements in security and performance
  • Flight recorder : The flight recorder was a commercial version JDK An analytical tool for , But in Java 11 in , Its code is included in the public code base , So that everyone can use the function

Java12

enhance Switch

  • Conventional switch Grammar is easy to miss break The problem of , And in terms of code neatness , Multiple break The essence is also a kind of repetition
  • Java12 Provides swtich expression , Use similar lambda The execution block after the syntax condition matches successfully , No need to write more break
  • Added as preview property , Need to be in javac Compiling and java Add parameters at runtime --enable-preview

    switch (day) { case MONDAY, FRIDAY, SUNDAY -> System.out.println(6); case TUESDAY -> System.out.println(7); case THURSDAY, SATURDAY -> System.out.println(8); case WEDNESDAY -> System.out.println(9);
    }

Number formatting tool class

  • NumberFormat  Added support for formatting complex numbers

NumberFormat fmt = NumberFormat.getCompactNumberInstance(Locale.US, NumberFormat.Style.SHORT);
String result = fmt.format(1000);
System.out.println(result); // Output is 1K, Calculate the wage K More convenient for ...

Shenandoah GC

  • Redhat Leading the development of Pauseless GC Realization , The main goal is 99.9% The pause of is less than 10ms, Pauses are not related to heap size, etc
  • and Java11 Open source ZGC comparison ( Need to upgrade to JDK11 Can be used ),Shenandoah GC There are stable JDK8u edition , stay Java8 Today's market share is greater

G1 Collector lift

  • Java12 For the default garbage collector G1 Brought two updates :

    • A collection of aborted mixed collections :JEP344 The implementation of the , In order to achieve the pause time target provided by the user ,JEP 344 By collecting the areas to be recycled ( Mixed collection collection ) Split into mandatory and optional parts , send G1 The garbage collector can stop the garbage collection process . G1 The recycle of optional parts can be stopped to achieve the pause time target
    • Return unused allocated memory in time :JEP346 The implementation of the , enhance G1 GC, In order to automatically put Java Heap memory is returned to the operating system

Java13

introduce yield Keywords to Switch in

  • Switch  There is one more keyword in the expression to jump out of  Switch  Key words for block  yield, Mainly used to return a value
  • yield and  return  The difference is that :return  Will jump directly out of the current loop or method , and  yield  Will only jump out of the current  Switch  block , In use at the same time  yield  when , Need to have  default  Conditions

    private static String descLanguage(String name) { return switch (name) { case "Java": yield "object-oriented, platform independent and secured"; case "Ruby": yield "a programmer's best friend"; default: yield name +" is a good language";

        };

    }

Text block

  • solve Java When defining a multiline string, you can only use a new line escape or a new line connector to work around the supported problems , Introduce triple double quotation marks to define multiline text
  • Two """ Anything in the middle is interpreted as part of the string , Include line breaks

    String json ="{n" +

              "   "name":"mkyong",n" +
              "   "age":38n" +
              "}n";   //  Before text block is not supported 
    
    

String json = """
{ "name":"mkyong", "age":38 } """; 

enhance ZGC Free up unused memory

  • stay Java 11 Is the experimental introduction of ZGC In actual use, there is a problem that the unused memory can not be released to the operating system
  • ZGC A heap is made up of a group called ZPages The stack area of . stay GC Empty in cycle ZPages Regional time , They will be released and returned to the page cache  ZPageCache  in , In this cache ZPages According to the latest minimum use (LRU) The order of , And organize by size
  • stay Java 13 in ,ZGC Pages marked as unused for a long time will be returned to the operating system , So that they can be reused by other processes

SocketAPI restructure

  • Java 13 by Socket API It brings a new way to realize the bottom layer , And in Java 13 The default is to use the new Socket Realization , Make it easy to find and increase maintainability while eliminating problems

Dynamic application classes - Data sharing

  • Java 13 Chinese vs Java 10 Introduced in Application class data sharing is further simplified 、 Improve and expand , namely : Allow in Java Dynamic class archiving at the end of application execution , Specific classes that can be archived include : All loaded , But it doesn't belong to the default base CDS Application classes and reference classes in the class library

Java14

record keyword

  • Simplify the way data classes are defined , Use record Instead of class Defined classes , Just declare the properties , You can get the access method of the property , as well as toString,hashCode,equals Method
  • It's similar to using Class Defining classes , At the same time lomobok plug-in unit , And I typed @Getter,@ToString,@EqualsAndHashCode annotation
  • Introduced as a preview feature

    /* This class has two characteristics

      1. All member properties are final
      1. All methods are constructed by , And two member property accessors ( Three in total )
    • Then this kind of class is very suitable for record To declare */
final class Rectangle implements Shape { final double length; final double width; public Rectangle(double length, double width) { this.length = length; this.width = width;
    } double length() { return length; } double width() { return width; }
} /** * 1.  Use record The declared class will automatically own the three methods in the above class 
 * 2.  On this basis, it is also attached equals(),hashCode() Methods and toString() Method 
 * 3. toString Method includes the string representation of all member properties and their names  */ record Rectangle(float length, float width) { }

The null pointer is extremely accurate

  • adopt JVM Add... To the parameter -XX:+ShowCodeDetailsInExceptionMessages, You can get more detailed call information in the null pointer exception , Faster positioning and problem solving

    a.b.c.i = 99; // Suppose that this code will have a null pointer

Exception in thread "main" java.lang.NullPointerException:

    Cannot read field 'c' because 'a.b' is null.
at Prog.main(Prog.java:5) //  In the exception prompted after adding the parameter, it is very clear where null causes 

switch Finally, the strengthening of the company became a full-fledged

  • JDK12 Introduced switch( Preview features ) stay JDK14 Become the official version , No need to add parameters to enable , Directly in JDK14 You can use
  • Mainly used -> To replace the old :+break; The other is to provide yield Come on block Medium return value

Before Java 14

switch (day) { case MONDAY: case FRIDAY: case SUNDAY:

    System.out.println(6); break; case TUESDAY:
    System.out.println(7); break; case THURSDAY: case SATURDAY:
    System.out.println(8); break; case WEDNESDAY:
    System.out.println(9); break;

}

Java 14 enhancements

switch (day) { case MONDAY, FRIDAY, SUNDAY -> System.out.println(6); case TUESDAY -> System.out.println(7); case THURSDAY, SATURDAY -> System.out.println(8); case WEDNESDAY -> System.out.println(9);
}

instanceof enhance

  • instanceof It mainly detects the specific type of the object before the type strong turn , Then carry out specific forced transfer
  • New version of the instanceof The conversion can be completed at the same time of judging whether the specific type belongs to

Object obj = " I'm a string "; if(obj instanceof String str){

System.out.println(str);

}

Other features

  • from Java11 Introduced ZGC As a successor G1 The next generation GC Algorithm , From support Linux Platform to Java14 Start supporting MacOS and Window( My personal feeling is that I can finally experience it first in the daily development tools ZGC The effect has been achieved. , Although in fact G1 Enough for )
  • Removed CMS Garbage collector ( After success, I will go back )
  • Added jpackage Tools , As standard, the application will be marked as jar Outside the package , It also supports feature packs for different platforms , such as linux Under the deb and rpm,window Under the platform msi and exe

summary

About preview features

  • Post a paragraph first oracle Official website :This is a preview feature, which is a feature whose design, specification, and implementation are complete, but is not permanent, which means that the feature may exist in a different form or not at all in future JDK releases. To compile and run code that contains preview features, you must specify additional command-line options.
  • This is a preview function , The design of this function , Specifications and implementation are complete , But not forever , This means that the feature may exist in other forms or in the future JDK There is no such thing as . To compile and run code with preview capabilities , Other command line options must be specified .
  • So switch For example , from Java12 Launched in , To Java13 Will continue to enhance , until Java14 Only then officially became a full-time official JDK Safe to use , Don't think about the follow-up JDK A change or modification to it
  • On the one hand, we can see that JDK Rigor as a standard platform for adding new features , On the other hand, I think that we should take a prudent attitude towards preview features . Features are easy to design and implement , But its actual value still needs to be verified in use

JVM Virtual machine optimization

  • Every time Java The release of the version is accompanied by the right JVM Optimization of virtual machine , Including the improvement of existing garbage collection algorithm , Introduce new garbage collection algorithm , Remove old garbage collection algorithms that are no longer applicable today
  • The direction of overall optimization is efficiency , Low latency garbage collection performance
  • For everyday application developers, they may pay more attention to new syntax features , But from a company perspective , Considering whether to upgrade Java More consideration is given to JVM Run time improvements

reference information

版权声明
本文为[JAVA_ Mr. Park]所创,转载请带上原文链接,感谢

Scroll to Top