Just a few days ago, Oracle officially announced that Java 11 (18.9 LTS) is now available for production use! This is undoubtedly good news for us. As a Java developer, it’s nice to learn and understand Java 11. I think at least you and I the same mood: Java in hand, the world I have!

Today we’ll take a look at what Java 11 is, what’s special about it, and whether or not to upgrade to Java 11.

What’s so special about Java 11

Java SE 11 (LTS) is the first version of the Java SE 11 (LTS) that is available for download.

The biggest differences between Java 11 and Java 9, which was released in September 2017, and Java 10, which was released in March 2018: In terms of long-term Support, Oracle has announced that Java 11 will be strongly supported until September 2026. This is the first long-term version supported since Java 8.

For the long term version, see the official support route chart below.

Above is an example of Oracle’s Support Roadmap for the JDK. The route lists the official release dates and support plans for Java 6-Java 12.

As you can see, prior to Java 11, Java 9 and Java 10 were not provided with long-term support, and the last version to provide long-term support was Java 8, which will be available until March 2025.

Long-term support: Oracle will provide long-term patches, security and other extension support.

The next release to provide long-term support will be Java 17, which will be released in 2021.

Java 8 and Java 9 and Java 10 are mostly used now, and very few people are using them now, at least I don’t see any companies using them in production, and that’s a dead end.

Now that Java 11 has long been supported and includes all of the features of 9 and 10, 9 and 10 have come to an end.

So what are the important new features from Java 9-11?

New features

1. Local variable type inference

What is local variable type inference?

var javastack = "javastack";  
System.out.println(javastack); 
Copy the code

As you can see, local variable type inference means that the type on the left is defined directly using var instead of writing the specific type, and the compiler can automatically infer the type from the expression on the right, such as String above.

var javastack = "javastack"Copy the code

Is equal to:

String javastack = "javastack"Copy the code

2. String reinforcement

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

// Check whether the string is blank"".isBlank();                // true// Remove the first and last Spaces" Javastack ".strip();          // "Javastack"// Remove trailing whitespace" Javastack ".stripTrailing();  // " Javastack"// Remove the header space" Javastack ".stripLeading();   // "Javastack "// Copy the string"Java".repeat(3);             // "JavaJavaJava"// Row count statistics"A\nB\nC".lines().count(); / / 3Copy the code

3. Aggregation is strengthened

Since Java 9, the Jdk has added “of” and “copyOf” methods to collections (List/ Set/ Map). Both methods are used to create immutable collections.

Example 1:

var list = List.of("Java"."Python"."C");  

var copy = List.copyOf(list);  

System.out.println(list == copy);   // true 
Copy the code

Example 2:

var list = new ArrayList<String>();  

var copy = List.copyOf(list);  

System.out.println(list == copy);   // false 

Copy the code

Example 1 is similar to example 2. Why is one true and the other false?

Take a look at their source code:

static <E> List<E> of(E... elements) {  

    switch (elements.length) { // implicit null check of elements  

        caseZero:return ImmutableCollections.emptyList();  

        case 1:  

            return new ImmutableCollections.List12<>(elements[0]);  

        case 2:  

            return new ImmutableCollections.List12<>(elements[0], elements[1]);  

        default:  

            return new ImmutableCollections.ListN<>(elements);  

    }  

}  

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

    return ImmutableCollections.listCopy(coll);  

}  

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

    if(coll instanceof AbstractImmutableList && coll.getClass() ! = SubList.class) {return (List<E>)coll;  

    } else {  

        return(List<E>)List.of(coll.toArray()); }}Copy the code

As you can see, the copyOf method first determines whether the source collection is an AbstractImmutableList type. If so, it returns an AbstractImmutableList. If not, it calls of to create a new collection.

Example 2: Because the collection created with new is not a subclass of the immutable AbstractImmutableList class, the copyOf method creates a new instance, so it is false.

Note: use of and copyOf create set for immutable, can not add, delete, replace, sorting and other operations, or you will quote Java lang. UnsupportedOperationException anomalies.

The above illustrates the of and copyOf methods for List, as well as the Set and Map interfaces.

4. Stream enhancement

Stream is a new feature in Java 8, and Java 9 began adding the following four new methods to Stream.

  1. Adds a single parameter constructor, which can be null
Stream.ofNullable(null).count(); / / 0Copy the code
  1. Add takeWhile and dropWhile methods
Stream.of(1, 2, 3, 2, 1) .takeWhile(n -> n < 3) .collect(Collectors.toList()); / / [1, 2]Copy the code

We start at the beginning, and we stop when n is less than 3.

Stream.of(1, 2, 3, 2, 1) .dropWhile(n -> n < 3) .collect(Collectors.toList()); / / [3, 2, 1)Copy the code

This is the opposite of what we did up here, where we start counting as soon as n is less than 3.

3) Iterate heavily

The new overloading method for the iterate method lets you supply a Predicate that specifies when to end the iteration.

If you’re not familiar with Stream in JDK 8, check out the series of tutorials shared earlier.

5, Optional

Opthonal also adds a few cool methods, now it is very convenient to convert an Optional into a Stream, or give it an alternative when an empty Optional.

Optional.of("javastack").orElseThrow();     // javastack  

Optional.of("javastack").stream().count();  // 1  

Optional.ofNullable(null)  

    .or(() -> Optional.of("javastack"))  

    .get();   // javastack 
Copy the code

6. InputStream enhancement

InputStream finally has a very useful method: transferTo, which can be used to transfer data directly to an OutputStream, a common use when dealing with raw data streams, as shown in the following example.

var classLoader = ClassLoader.getSystemClassLoader();  

var inputStream = classLoader.getResourceAsStream("javastack.txt");  

var javastack = File.createTempFile("javastack2"."txt");  

try (var outputStream = new FileOutputStream(javastack)) {  

    inputStream.transferTo(outputStream);  

} 
Copy the code

7. HTTP Client API

This is an incubation HTTP Client API for handling HTTP requests that was introduced in Java 9. This API supports both synchronization and asynchrony, and was officially available in Java 11. You can find this API in the Java.net package.

Take a look at HTTP Client usage:

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()); / / the asynchronous client. SendAsync (request, HttpResponse.BodyHandlers.ofString()) .thenApply(HttpResponse::body) .thenAccept(System.out::println);Copy the code

The above.get () can be omitted. The default request mode is GET!

See this API for more examples, and I’ll show you later.

Now that Java comes with the HTTP Client API, will we need to use Apache’s HttpClient toolkit in the future?

To simplify, a command to compile and run the source code

Look at the code below.

// Compile javac Javastack. Java // Run Java JavastackCopy the code

In our understanding, to run a Java source code must first compile, then run, two steps to execute the action. In future Java 11 releases, this is done directly with a Single Java command, as shown below.

java Javastack.java 
Copy the code

More new features

The new Java 11 release includes 17 NEW JEP(JDK Enhancement Proposal) features.

Above is a look at all the new features that Oracle has announced for Java 11. Some of the key new features are:

ZGC: Extensible low latency garbage collector

ZGC is a garbage collector that claims to guarantee pauses of no more than 10MS per GC and throughput degradation of no more than 15% compared to G1, the current default garbage collection start.

Epsilon: A garbage collector that does nothing

Java 11 also adds a special garbage collector, Epsilon, which is called a “no-op” collector and will handle memory allocation without implementing any actual memory collection mechanism. In other words, this is a garbage collector that does not do garbage collection. This garbage collector does not seem to be very useful. It can be used for performance testing, memory stress testing, etc. Epsilon GC can be used as a control group to measure the performance of other garbage collectors. At the very least, says Martijn, the Epsilon GC will help to understand the GC interface and contribute to a more modular JVM.

Enhanced use of var

Java 10 added the feature of local variable type inference, using var to define local variables. Although this feature has been criticized by many, Java continues to enhance its usage. In Java 11, var can be used as a local variable declaration for Lambda expressions.

Remove Java EE and CORBA modules

At the time of the Java SE 9 release, Java said that the Java EE and CORBA modules would be removed in future releases, and this move has finally been implemented in Java 11. Java EE and CORBA modules are finally removed.

The HTTP client is further upgraded

The HTTP Client API was standardized in JDK 9, and then updated in JDK 10 via JEP 110. In this list of Java 11 updates, JEP 321 is a further upgrade. The API provides non-blocking request and response semantics through CompleteableFutures, which can be used in combination to trigger the appropriate action. JDK 11 completely rewrites this functionality. It is now easier to trace the flow of data between the user-level request and response publishers and the underlying socket, reducing complexity and maximizing the potential for reuse between HTTP / 1 and HTTP / 2.

Whether or not to upgrade

In August 2017, the JCP executive Committee proposed changing the frequency of Java releases to every six months.

  • In September 2017, Java 9 was released.
  • In March 2018, Java 10 was released.
  • In September 2018, Java 11 was released.

Most people still use Java 8 or later, and even some companies’ production environments use JDK 1.6.

So is it important for companies and developers to upgrade and learn Java 11 in production and development environments?

For the enterprise

For enterprises, it is still necessary to upgrade JDK versions in production environments to Java 11. There are two main reasons:

1. Oracle will provide long-term support for Java 11, so enterprises can safely use this version. And the next long term support version will be released in three years, which is quite a long time.

Java 11 does offer some nice features, most importantly ZGC, a landmark garbage collector. The advantages are omitted. With ZGC, JVM performance bottlenecks can be broken.

For developers

In terms of coding, Java 11 hasn’t changed as much as Java 8, which provides the ability to program in a functional way, which is one of the reasons many developers learned Java 8.

However, Java 11 is not completely unimproved, at least in the new version Java developers can finally get rid of the old HttpURLConnection. The new HTTP API provides support for leading edge standards such as HTTOP/2, providing a streamlined and friendly API interface.

So, to sum up, Java 11 is a necessary upgrade for both enterprises and developers, at least much more so than Java 9 and Java 10. As for the extent of this necessity, the author gives a simple explanation:

  • If you are currently using a JDK/Java version later than Java 8, upgrade to Java 8 first.
  • If you are currently using a JDK/Java version older than Java 7, consider upgrading to Java 11. Of course, you can jump directly from Java 6 to Java 11.

The last

A lot of people are still using Java 8 or 7, but 8 will end up being free in early 2019. Now that 11 is a long term support version, it’s a good time to learn and get started with 11. I’m writing this article in the hope that it will inspire you.

To read more

And this operation? Analysis why to see the source code

Last release VERSION I changed a line of code!

Advantages and disadvantages of NoSQL, such as MongoDB, Hbase, and Redis, and application scenarios

31 Android interview questions to build your foundation

Believe in yourself, nothing is impossible, only unexpected

It’s not just technology you get here!