Hello, I’m Guide! This article came from readers’ contributions, and after two major changes, two weeks of perfection was finally completed. What’s new in Java8 is here: The Best Guide to what’s New in Java8.

Guide brother: Other people’s features have been used for several years, I just came out of Java, ha ha! Real!

Java9

Posted on September 21, 2017. Released three and a half years after Java8, Java 9 brings with it a number of major changes, the most important of which is the introduction of the Java platform module system, along with other changes such as collections and Streams

Java platform module system

The Java platform module system, also known as Project Jigsaw, brings modular development practices to the Java platform. With the introduction of a module system, the JDK was reorganized into 94 modules. Java applications can use the new JLink tool to create custom runtime images that contain only the JDK modules they depend on. This can greatly reduce the size of the Java runtime environment.

An important feature of a Java 9 module is the inclusion of a module-info.class document describing the module in the root of its artifact. The format of the artifacts can be a traditional JAR file or a JMOD file added to Java 9.

Jshell

Jshell is a new utility in Java 9. Provides A python-like real-time command line interaction tool for Java.

In Jshell, you can type expressions directly and see the result of their execution

Collection, Stream, and Optional

  • increasedList.of(),Set.of(),Map.of()Map.ofEntries()And so on factory methods to create immutable collections, for exampleList.of("Java", "C++");,Map.of("Java", 1, "C++", 2); (This is a bit of a Guava reference.)
  • StreamNew methods have been added toofNullable,dropWhile,takeWhileiterateMethods.CollectorsNew methods have been added tofilteringflatMapping
  • OptionalClass is addedifPresentOrElse,orstreamMethods such as

Process API

Java 9 adds the ProcessHandle interface to manage native processes, especially long-running processes

Platform logging APIS and services

Java 9 allows you to configure the same logging implementation for both the JDK and applications. Added System.loggerFinder to manage logger implementations used by the JDK. The JVM has only one system-wide Instance of LoggerFinder at run time.

We can make JDK and applications use other logging frameworks such as SLF4J by adding our own Implementation of System.LoggerFinder.

Reactive Streams

  • In the Java9java.util.concurrent.FlowClass added a core interface for the reactive flow specification
  • The Flow containsFlow.Publisher,Flow.Subscriber,Flow.SubscriptionFlow.ProcessorWait for 4 core interfaces. Java 9 also providesSubmissionPublisherAs aFlow.PublisherAn implementation of.

Handle to the variable

  • A variable handle is a reference to a variable or group of variables, including static fields, non-static fields, array elements, and components in an off-heap data structure
  • Variable handles are similar in meaning to existing method handlesMethodHandle
  • By the Java classesjava.lang.invoke.VarHandleYou can use a classjava.lang.invoke.MethodHandles.LookupTo create the static factory method inVarHandleThe elephant

Improved Method Handle

  • Method handles were introduced starting with Java7, and Java9 in classesjava.lang.invoke.MethodHandlesMore static methods have been added to create different types of method handles

Other new features

  • Interface private Methods: Java 9 allows the use of private methods in interfaces
  • The try – with – resources enhancement: In the try – with – resources statement can be used effectively to final variables (what is effectively – final variables, see the article ilkinulas. Making. IO/programming…).
  • classCompletableFutureSeveral new methods (completeAsyncorTimeoutEtc.)
  • Nashorn engine enhancements: Nashorn introduced the JavaScript engine starting with Java8. Java9 made some enhancements to Nashorn and implemented some new ES6 features
  • New features for I/O streams: New methods have been added to read and copy data contained in InputStream
  • Improved application security: Java 9 has four new SHA-3 hashing algorithms, SHA3-224, SHA3-256, SHA3-384, and SHAha3-512
  • .

Java10

Released on March 20, 2018, the most notable feature is the introduction of the VAR keyword (local variable type inference), along with garbage collector improvements, GC improvements, performance improvements, thread control and a host of other new features

The var keyword

  • introduce: provides the var keyword to declare local variables:var list = new ArrayList<String>(); // ArrayList<String>
  • Limitations: Can only be used in local variables and for loops with constructors

Guide: Lombok actually already uses a similar keyword, which simplifies code but may make it less readable and maintainable. In general, I personally don’t recommend it.

Immutable set

List, set, and map provide static methodscopyOf()Return an immutable copy of the incoming parameter collection.

static <E> List<E> copyOf(Collection<? extends E> coll) {

    return ImmutableCollections.listCopy(coll);

}

Copy the code

java.util.stream.CollectorsStatic methods have been added to collect elements in a stream as immutable collections

Optional

  • A neworElseThrow()Method to throw an exception when there is no value

Parallel full garbage collector G1

G1 has been the default garbage collector since Java9. G1 was designed as a low-latency garbage collector, FullGC is designed to avoid FullGC, but Java9’s G1 FullGC still uses a single thread to complete the tag clearing algorithm, which can cause the garbage collection period to trigger FullGC when memory cannot be collected.

In order to minimize the impact of application pauses caused by FullGC, starting with Java10, FullGC in G1 is changed to a parallel marker clearing algorithm, which uses the same number of parallel worker threads as young generation and mixed collection, thus reducing the occurrence of FullGC. For better performance and greater throughput.

Application class data sharing

Class Data Sharing (CDS) was introduced in Java 5, allowing a set of classes to be preprocessed into a shared archive so that memory mapping can be done at runtime to reduce Java program startup time. When multiple Java virtual machines (JVMS) share the same archive file, it also reduces dynamic memory usage and resource usage when multiple virtual machines are running on the same physical or virtual machine

Java 10 extends the existing CDS functionality to allow application classes to be placed in a shared archive. The CDS feature is extended to include Application class-data Sharing (CDS) support from the Application Class based on the bootstrap Class. The principle is as follows: the process of loading classes is recorded during startup and written into a text file. The startup text is directly read and loaded when it is started again. Imagine that the startup speed would increase if the application environment did not change significantly

Other features

  • Thread-local control: Thread control introduced in Java 10, the concept of JVM safety points, will allow thread callbacks to be implemented without running global JVM safety points, either by the thread itself or by the JVM thread, while keeping the thread blocked, in a way that makes it possible to stop a single thread rather than just start or stop all threads

  • Heap allocation on standby storage: Java 10 will enable the JVM to allocate heap memory on optional memory devices using heaps suitable for different types of storage mechanisms

  • Unified garbage collection interface: In Java 10, hotspot/ GC code implementation aspects introduced a clean GC interface, improved isolation of different GC source code, implementation details shared between multiple GCS should exist in helper classes. The main reason for unifying the garbage collection interface is to make the garbage collector (GC) part of the code cleaner and easier for newcomers to get started and troubleshoot related problems later.

Java11

Java11 was released on September 25, 2018, and it’s an important release! The biggest differences between Java 11 and Java 9, released in September 2017, and Java 10, released in March 2018, are: In terms of long-term Support, Oracle said it will provide strong Support for Java 11 through September 2026. This is the first long-term release supported since Java 8.


String reinforcement

Java 11 adds a number of string handling methods, as shown below.

Guide brother: To put it plainly, there are many layers of encapsulation, and the JDK development team has seen a lot of common tool class frameworks in the market.

// Determine if the string is empty

"".isBlank();//true

// Remove Spaces at the beginning and end of strings

" Java ".strip();// "Java"

// Remove the space at the beginning of the string

" Java ".stripLeading();   // "Java "

// Remove the space at the end of the string

" Java ".stripTrailing();  // " Java"

// How many times to repeat the string

"Java".repeat(3);             // "JavaJavaJava"



// Returns a collection of strings separated by line terminators.

"A\nB\nC".lines().count();    / / 3

"A\nB\nC".lines().collect(Collectors.toList()); 

Copy the code

ZGC: Scalable low-latency garbage collector

ZGC, or Z Garbage Collector, is a scalable, low-latency Garbage Collector.

The ZGC is designed to meet the following objectives:

  • The GC pause time does not exceed 10ms
  • It can handle small heaps of several hundred MEgabytes or large heaps of several terabytes
  • – Application throughput will not drop by more than 15% (compared to G1 recycle)
  • It is easy to introduce new GC features and make use of COLord on this basis
  • Needle and Load barriers optimization lay the foundation
  • Currently, only Linux/ X 64-bit platforms are supported

ZGC is currently experimental and only supports Linux/ X64 platforms

Standard HTTP Client upgrade

Java 11 standardizes the Http Client API introduced in Java 9 and updated in Java 10. While incubated in the previous two versions, the Http Client was almost completely rewritten and now fully supports asynchronous non-blocking.

Also, in Java11, the package name of the Http Client was changed from JDK.incubate.http to java.net.http, an API that provides non-blocking request and response semantics through CompleteableFuture.

It is also very simple to use, as follows:

var request = HttpRequest.newBuilder()  



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



    .GET()  



    .build();  



var client = HttpClient.newHttpClient();  



/ / synchronize



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); 





Copy the code

Simplify the way to launch a single source code file

  • Enhanced Java launcher to run Java source code from a single file. This feature allows you to execute Java source code directly using the Java interpreter. The source code is compiled in memory and then executed by the interpreter. The only constraint is that all related classes must be defined in the same Java file
  • It is especially useful for Java beginners who want to try simple programs, and can be used with JShell
  • The ability to write scripts in Java has been somewhat enhanced

Local variable syntax for Lambda arguments

  • The key feature of local variable type inference has been introduced since Java 10. Type inference allows the keyword var to be used as the type of a local variable rather than the actual type, and the compiler to infer the type from the value assigned to the variable
  • There are several restrictions on the VAR keyword in Java 10
    • Can only be used on local variables
    • Must be initialized when declared
    • Cannot be used as a method parameter
    • Cannot be used in Lambda expressions
  • Java11 began to allow developers to use var for parameter declarations in Lambda expressions

Other features

  • The new garbage collector Epsilon, a completely passive GC implementation, allocates limited memory resources to minimize memory footprint and memory throughput latency
  • Low-overhead Heap Profiling: Java 11 provides a low-overhead Java Heap allocation sampling method that can obtain Heap allocation Java object information and access Heap information through JVMTI
  • TLS1.3 protocol: Java 11 includes an implementation of the Transport Layer Security (TLS) 1.3 specification (RFC 8446), which replaces TLS included in previous versions, including TLS 1.2, as well as other TLS enhancements such as the OCSP binding extensions (RFC 6066, RFC 6961), As well as session hashing and extended master Key extension (RFC 7627), there are also many security and performance improvements
  • Flight Recorder: Flight Recorder was previously an analysis tool in the commercial JDK, but in Java 11 its code is included in the public code base so that anyone can use it

Java12

Enhance the Switch

  • Traditional switch syntax is prone to missing breaks, and multiple breaks are inherently repetitive in terms of code cleanliness

  • Java12 provides swtich expressions that use lambda-like syntax to execute blocks after a successful match, without the need to write more breaks

  • Added as a preview feature, enable-Preview is required for javac compilation and Java runtime

    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);

    }

    Copy the code

Number formatting utility 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); // The output is 1K.

    Copy the code

Shenandoah GC

  • Redhat led development of the Pauseless GC implementation, the main goal is 99.9% pauses less than 10ms, pauses independent of heap size, etc
  • Compared to the Java11 open source ZGC (which requires an upgrade to JDK11 to be used), Shenandoah GC has a stable JDK8u version and is more scalable in a world where Java8 has a major market share

G1 collector promotion

  • Java12 brings two updates to the default garbage collector G1:
    • Abortable mixed collection: Implementation of JEP344, which enables the G1 garbage collector to abort the garbage collection process by splitting the set of regions to be collected (the mixed collection) into mandatory and optional parts in order to meet the user-provided pause time goal. G1 can abort the collection of optional portions to meet the pause time goal
    • Timely return of unused allocated memory: Implementation of JEP346 that enhances G1 GC to automatically return Java heap memory to the operating system when idle

Java13

Introduce the yield keyword into the Switch

  • The Switch expression uses the yield keyword to jump out of the Switch block, which returns a value

  • The difference between yield and return is that return will jump out of the current loop or method directly, whereas yield will jump out of the current Switch block only, and the default condition is required when using yield

     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";

            };

     }

    Copy the code

Text block

  • To solve the problem that Java can only define multi-line strings by newline escape or newline concatenation, we introduce triple double quotes to define multi-line text

  • Anything between “” and “” is interpreted as part of the string, including newlines

    String json ="{\n" +

                  " \"name\":\"mkyong\",\n" +

                  " \"age\":38\n" +

                  "}\n";   // Before text blocks are supported

    Copy the code


     String json = """

                    {

                        "
    name":"mkyong",

                        "
    age38 ":

                    }

                    "
    "";

    Copy the code

Enhanced ZGC to free unused memory

  • Introduced experimentally in Java 11, the ZGC fails to proactively free unused memory to the operating system in real life
  • The ZGC heap consists of a set of heap areas called ZPages. When the ZPages area is emptied during a GC cycle, they are freed and returned to the page cache ZPageCache, which holds ZPages in least-recently used (LRU) order and organized by size
  • In Java 13, THE ZGC returns pages to the operating system that have been identified as unused for a long time so that they can be reused by other processes

SocketAPI refactoring

  • Java 13 brings a new low-level implementation of the Socket API, and the new Socket implementation is used by default in Java 13, making it easy to find and troubleshoot problems while increasing maintainability

Dynamic application classes – data sharing

  • Application class data sharing introduced in Java 10 is further simplified, improved, and extended in Java 13 to allow dynamic class archiving at the end of Java application execution. Classes that can be archived include: All the application classes and reference classes in the library that have been loaded but are not part of the default base CDS

Java14

Record the keyword

  • To simplify the definition of data classes, use record instead of class definition of the class, only need to declare the attribute, can obtain the attribute access method, and toString, hashCode,equals methods

  • Similar to using Class to define a Class, using lomobok plug-ins and annotating @getter, @toString, @EqualSandHashCode

  • Introduced as a preview feature

    / * *

    * This class has two characteristics

    * 1. All member attributes are final

    * 2. The entire method consists of a constructor and two member attribute accessors (three in total).

    * Then this class is a good place to declare using Record

    * /


    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(a) return length; }

        double width(a) return width; }

    }

    / * *

    * 1. Classes declared using Record automatically own the three methods of the above class

    * 2. Add the equals(), hashCode(), and toString() methods to the list

    * 3. The toString method contains the string representation of all member attributes and their names

    * /


    record Rectangle(float length, float width) {}

    Copy the code

The null pointer is abnormally accurate

  • Through the JVM parameter add – XX: + ShowCodeDetailsInExceptionMessages, can in a null pointer exception calls for more detailed information, faster to locate and solve the problem

    a.b.c.i = 99// Assume that null Pointers occur in this code

    Copy the code
    Exception in thread "main" java.lang.NullPointerException:

            Cannot read field 'c' because 'a.b' is null.

        at Prog.main(Prog.java:5// Where is the null result

    Copy the code

Enhancements to the Switch have finally turned positive

  • The switch (preview feature) introduced in JDK12 becomes official in JDK14 and can be used directly in JDK14 without additional parameters
  • Mainly is to use->To replace the old one:+break; In addition, yield is provided to return a value in a block

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;

}

Copy the code

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);

}

Copy the code

Instanceof enhancement

  • Instanceof primarily probes the concrete type of an object before type coercion, and then performs the concrete coercion

  • The new instanceof version can perform the conversion while determining whether an object belongs to a specific type

Object obj = "I'm a string";

if(obj instanceof String str){

 System.out.println(str);

}

Copy the code

Other features

  • ZGC introduced from Java11 as the next generation of GC algorithm after G1, from support Linux platform to Java14 began to support MacOS and Windows (personal feeling is finally able to experience the effect of ZGC in the daily development tools, Although the G1 is good enough.)
  • Removing the CMS garbage collector
  • The jPackage tool has been added to support applications in addition to jar packages, as well as feature packages for different platforms, such as LinuxdebandrpmWindowsmsiandexe

conclusion

About preview Features

  • Oracle: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 feature, and the design, specification, and implementation of this feature is complete, but not permanent, meaning that this feature may exist in some other form or not exist at all in a future JDK release. To compile and run code that includes preview functionality, you must specify additional command-line options.
  • asswitchFor example, Java12 enhancements will continue to be implemented in Java13, until Java14 is officially incorporated into the JDK and can be used without regard to changes or modifications made to it in subsequent JDK releases
  • On the one hand, we can see that the JDK is serious about adding new features as a standard platform. On the other hand, I think we should be cautious about using preview features. Features are easy to design and implement, but their actual value still needs to be verified in use

JVM VM optimization

  • Each release of Java has been accompanied by improvements to the JVM virtual machine, including improvements to existing garbage collection algorithms, introduction of new garbage collection algorithms, removal of old garbage collection algorithms that are no longer suitable for today, and so on
  • The overall optimization direction is efficient, low latency garbage collection performance
  • For everyday application developers, new syntax features may be on the radar, but from a corporate perspective, improvements to the JVM runtime are more important when considering whether to upgrade the Java platform

The reference information

  • IBM Developer Java9 www.ibm.com/developerwo…
  • Guide to Java10 www.baeldung.com/java-10-ove…
  • Java 10 new Features www.ibm.com/developerwo…
  • IBM Devloper Java11 www.ibm.com/developerwo…
  • Java 11 – the Features and Comparison: www.geeksforgeeks.org/java-11-fea…
  • Oracle Java12 ReleaseNote www.oracle.com/technetwork…
  • Oracle Java13 ReleaseNote www.oracle.com/technetwork…
  • New Java13 the Features www.baeldung.com/java-13-new…
  • Overview of new Java13 features www.ibm.com/developerwo…
  • Oracle Java14 record docs.oracle.com/en/java/jav…
  • Java14 – the features www.techgeeknext.com/java/java14…

This article is formatted using MDNICE