• “MoreThanJava” is about “learning, not just CODE”. This series of Java basics tutorials is a general review of the basics of Java by myself after combining all aspects of knowledge, aiming to “help new friends learn quickly and with high quality”.
  • Of course, both old and new, I believe you will benefit from it. If you feel “good” friends, welcome to “follow + message + share”, at the end of the article there is a complete link to get, your support is the biggest motivation for me to move forward!

Why is Java 11 important?

Java 11 is the second LTS (long-term Support) release after Java 8. As of Java 11, the Oracle JDK will no longer be freely available for commercial use.

You can use it during development, but to use it commercially, you need to purchase a license.

Java 10 is the last free Oracle JDK available for download.

Oracle discontinued support for Java 8 in January 2019. You need to pay more support fees.

If you don’t, you won’t get any patches/security updates, although you can continue to use it.

As of Java 11, Oracle will no longer provide free long Term support (LTS) for any single Version of Java.

Although the Oracle JDK is no longer free, you can always get it from Oracle or other providers (e.g. AdoptOpenJDK, Azul, IBM, Red Hat, etc..) Download the Open JDK build.

What is an LTS Module

Beginning in 2017, Oracle and the Java community announced a shift to a new six-month rhythm for Java. It has migrated to the Oracle Java SE product’s Long Term Support (LTS) model.

The LTS version of the product will provide primary and ongoing support for Oracle, with a goal of once every three years.

Each Java release is modeled on one or two major features that drive the release. Any obstacle could delay the launch and launch. The Jigsaw project, a major feature of Java 9, has been pushed back several times and has been pushed back by more than 1.5 years. The pace of the 6-month launch will allow features to follow. The trains released have a schedule every 6 months. Catching the train’s signature is left behind, otherwise they wait for the next train.

Oracle JDK and Open JDK

To be more developer-friendly, the Oracle & Java community now promotes the OpenJDK binaries as the primary JDK.

This is much less burdensome than the earlier JDK binaries, which were proprietary and licensed by Oracle, because Oracle had various restrictions on redistribution.

However, Oracle will continue to produce their JDK, but only in long-supported versions. This is a step in the direction of being more cloud – and container-friendly, because open JDK binaries can be distributed as part of the container.

Binaries for the Open JDK are released every 6 months, while binaries for the Oracle JDK are released every 3 years (the LTS version).

Features overview

Now that you’ve seen the burdens that come with Java 11, let’s take a look at the important features in Java 11 as developers.

The following are some of the new features introduced in Java 11. A more detailed description of the new Java 11 features can be found here.

  • Nested Based Access Control (JEP 181)
  • Running a Java file with a single command (JEP 330)
  • Local Variable Syntax for Lambda arguments (JEP 323)
  • Dynamic Class file Constants (JEP 309)
  • HTTP Client (JEP 321)
  • Epsilon- Operation-free Garbage Collector (JEP 318)
  • Extensible Low-latency Garbage Collector -ZGC (JEP 333)
  • Unicode 10 (JEP 327)
  • Low-overhead Heap Analysis (JEP 331)
  • API changes
  • Other changes
    • Delete Java EE and CORBA modules (JEP 320)
    • Flight Recorder (JEP 328)
    • ChaCha20 and Poly1305 Encryption Algorithms (JEP 329)
    • Improved Aarch64 internal Features (JEP 315)
    • Deprecated Nashorn JavaScript Engine (JEP 335)
    • Transport Layer Security (TLS) 1.3 (JEP 332)
    • Deprecating Pack200 tools and apis (JEP 336)

1. Nested Based Access Control (JEP 181)

Prior to Java 11, it was possible to access private methods of the main class from nested classes:

public class Main {
 
    public void myPublic(a) {}private void myPrivate(a) {}class Nested {

        public void nestedPublic(a) { myPrivate(); }}}Copy the code

However, if we use reflection, it will give an IllegalStateException:

jshell> Main ob = new Main();
ob ==> Main@533ddba

jshell> import java.lang.reflect.Method;

jshell> Method method = ob.getClass().getDeclaredMethod("myPrivate"); method ==> private void Main.myPrivate() jshell> method.invoke(ob); | exception error Java. Lang. IllegalAccessException: class REPL. $JShell$15 cannot access a member of class REPL.$JShell$11$Main with modifiers "private"
|        at Reflection.newIllegalAccessException (Reflection.java:376)
|        at AccessibleObject.checkAccess (AccessibleObject.java:647)
|        at Method.invoke (Method.java:556)
|        at (# 5 to 1)

jshell>
Copy the code

This is because JVM access rules do not allow private access between nested classes. We can access it the first way because the JVM implicitly creates private bridge methods for us at compile time.

And it happens behind the scenes. This bridging approach slightly increases the size of the deployed application and can confuse users and tools.

Java 11 addresses this problem by introducing nested access control.

Java 11 introduced the concept of nesting and associated access rules to the JVM. This simplifies the work of the Java source code compiler.

To do this, the class file format now contains two new properties:

  1. A nested member (usually a top-level class) is designated as the nested main class. It contains an attribute (NestMembers) to identify other statically known nested members.
  2. Each other nested member has a property (NestHost) that identifies its nested main class.

Therefore, for types C and D to be nested partners, they must have the same nested main class. If type C lists D in its NestHost attribute, it claims to be a nested member of D’s hosting. If D also lists C in its NestMembers property, membership is verified. In addition, type D is implicitly a nested member that it hosts.

Now, the compiler does not need to generate the bridge method.

Java.lang.class introduces three methods in the reflection API: getNestHost(), getNestMembers(), and isNestmateOf() to support the above work.

Read more: www.baeldung.com/java-nest-b…

Ii. Running a Java file with a single command (JEP 330)

The JEP was a friendly feature in the early stages of learning Java, but it wasn’t much use in actual Java development, where we all use ides.

Suppose we now have the following source code (.java file) :

public class HelloJava {

    public static void main(String[] args) {
        System.out.println("Hello World!"); }}Copy the code

To compile and run in Java 11:

$ javac HelloJava.java

$ java HelloJava

Hello World!
Copy the code

In Java 11:

$ java HelloJava.java

Hello World!
Copy the code

Alternatively, we can run a single Java program using Linux Shebang:

#! /opt/java/openjdk/bin/java --source 11
public class SheBang {

    public static void main(String[] args) {

        System.out.println("Hello World!"); }}Copy the code

Here is an example of using Linux Shebang to run Java in Docker like this: mkyong.com/java/java-1…

Local Variable Syntax for Lambda Parameters (JEP 323)

The JEP is the only language feature enhancement in Java 11.

As we know, local variable type inference was introduced in Java 10. So, we can infer the type of the variable from RHS: var list = new ArrayList

();

JEP 323 allows var to be used to declare formal arguments to implicitly typed Lambda expressions:

List<String> list = Arrays.asList("Attention"."I don't have three hearts."."More exciting content to share");
String result = list.stream()
        .map((var x) -> x.toUpperCase())
        .collect(Collectors.joining(","));
System.out.println(result2);
Copy the code

The above is equivalent to the following:

List<String> list = Arrays.asList("Attention"."I don't have three hearts."."More exciting content to share");
String result = list.stream()
        .map(x -> x.toUpperCase())
        .collect(Collectors.joining(","));
Copy the code

This (omiting the form of type declarations) was also allowed in Java 8 but removed in Java 10. It is now back in Java 11 for consistency.

Why is var supported to declare implicit Lambda arguments? (especially if we only need to skip Lambda types)

The answer is that if you want to comment parameters like @notnull, you cannot do so without defining the type:

import org.jetbrains.annotations.NotNull;

List<String> list = Arrays.asList("Attention"."I don't have three hearts."."More exciting content to share".null);
String result = list.stream()
  .map((@NotNull var x) -> x.toUpperCase())
  .collect(Collectors.joining(","));
System.out.println(result3);
Copy the code

This feature has some limitations — you must specify the var type on all parameters, or none at all.

None of the following is possible in a parameter declaration used inside a Lambda:

(var s1, s2) -> s1 + s2 //no skipping allowed
(var s1, String y) -> s1 + y //no mixing allowed

var s1 -> s1 //not allowed. Need parentheses if you use var in lambda.
Copy the code

4. Dynamic Class File Constants (JEP 309)

To make the JVM more attractive to dynamic languages, Java SE 7 has introduced InvokeDynamic into its instruction set. Java developers typically do not notice this feature because it is hidden in Java bytecode.

In short, by using InvokeDynamic, you can defer the binding of a method call until the first invocation.

For example, the Java language uses this technique to implement Lambda expressions that need to appear only when first used.

Thus invokedynamic has evolved into a basic language function. In constantdynamic, Java 11 introduces a similar mechanism, except that it delays the creation of constant values.

Java 11 itself lacks support for constantdynamic, so I won’t go into details here.

The purpose of this article in detail discussed the characteristics and working principle of the internal, and shows how to use the Byte Buddy library generated using this new instruction code, interested can read: mydailyjava.blogspot.com/2018/08/han…

5. HTTP Client (JEP 321)

Java 11 standardizes the Http CLient API.

The new API supports HTTP / 1.1 and HTTP / 2. It is designed to improve the overall performance of clients sending requests and receiving responses from the server. It also supports WebSockets natively.

Here is an example of sending a simple GET request using Java 11 HttpClient:

HttpClient httpClient = HttpClient.newBuilder()
        .version(HttpClient.Version.HTTP_1_1)
        .connectTimeout(Duration.ofSeconds(10))
        .build();

HttpRequest request = HttpRequest.newBuilder()
        .GET()
        .uri(URI.create("https://www.wmyskxz.com"))
        .setHeader("User-Agent"."Java 11 HttpClient Bot")
        .build();

HttpResponse<String> response = httpClient.send(request, HttpResponse.BodyHandlers.ofString());

HttpHeaders headers = response.headers();
headers.map().forEach((k, v) -> System.out.println(k + ":" + v));

System.out.println(response.statusCode());
System.out.println(response.body());
Copy the code

Read more about HttpClient: mkyong.com/java/java-1…

Epsilon- Operation-free Garbage Collector (JEP 318)

Unlike the JVM GC, which allocates and frees memory, Epsilon only allocates memory.

It allocates memory for the following:

  • Performance testing.
  • Memory stress test.
  • VM interface testing.
  • Jobs with very short life spans.
  • The last drop is delayed improvement. (Last-drop latency improvements.)
  • The resulting throughput increases.

For now, Elipson is only available in test environments. This causes an OutOfMemoryError in production and crashes the application.

The benefit of Elipson is that there is no memory cleaning overhead. Therefore, it will give accurate performance test results and we can no longer stop it by GC.

Note: This is an experimental function.

Vii. Extensible Low-latency Garbage Collector -ZGC (JEP 333)

The Z garbage collector (ZGC) is a scalable low-latency garbage collector. ZGCS can perform all expensive work simultaneously without stopping the execution of application threads for more than 10 milliseconds, making them suitable for applications that require low latency and/or use very large heaps (terabytes).

Z the garbage collector can be used as the experimental function, can through the command line options enabled – XX: + UnlockExperimentalVMOptions – XX: + UseZGC.

(PS: This garbage collector was only ready for production in JDK 15 — JEP 377 — so it’s probably not going to be used for a long time.)

OpenJDK-wiki:wiki.openjdk.java.net/display/zgc…

8. Unicode 10 (JEP 327)

Here are the new emojis available in the Unicode 10.0 release:

You can see the details of the Unicode 10.0 update here, which can be summarized as follows:

“Unicode 10.0 adds 8,518 characters for a total of 136,690 characters. These additions include four new scripts for a total of 139 scripts, and 56 new emoji characters.”

Code demo:

public class PrintUnicode {

    public static void main(String[] args) {
        String codepoint = "U+1F92A";   // crazy face
        System.out.println(convertCodePoints(codepoint));
    }

    // Java, UTF-16
    // Convert code point to unicode
    static char[] convertCodePoints(String codePoint) {
        Integer i = Integer.valueOf(codePoint.substring(2), 16);
        char[] chars = Character.toChars(i);
        returnchars; }}Copy the code

Good article recommendation:

In Java using Unicode fun: www.codetab.org/post/java-u…

This article covers the basics of encoding and decoding and Unicode in detail, as well as detailed examples of using Unicode in Java programming.

Low Overhead Heap Analysis (JEP 331)

The Java Virtual Machine Tool Interface (JVM TI), introduced in Java SE 5, monitors the execution of events within the JVM and also controls certain behavior of the JVM, enabling debugging, monitoring, thread analysis, coverage analysis tools, and more.

This JEP adds a new low-overhead heap analysis API to JVM TI.

Further reading: Oracle JVM TI official document – docs.oracle.com/javase/8/do…

X. API changes

String new method

isBlank()

IsBlank () — This instance method returns a Boolean value. Empty strings and strings containing only Spaces are treated as empty.

import java.util.*;

public class Main {
    public static void main(String[] args) throws Exception {
        System.out.println("".isBlank()); //true
        
        String s = "wmyskxz";
        System.out.println(s.isBlank()); //false
        String s1 = "";
        System.out.println(s1.isBlank()); //true}}Copy the code

lines()

This method returns a string stream, which is a collection of all substrings split by line.

jshell> import java.util.stream.Collectors;

jshell> String str = "JD\nJD\nJD";
str ==> "JD\nJD\nJD"

jshell> System.out.println(str);
JD
JD
JD

jshell> System.out.println(str.lines().collect(Collectors.toList()));
[JD, JD, JD]

jshell>
Copy the code

strip() / stripLeading() / stripTrailing()

Strip () — Removes Spaces at the beginning and end of the string.

StripLeading () – deletes the header of the string.

StripTrailing () — Deletes the space at the end of the string.

jshell> String str = "I don't have three hearts.";
str ==> "I don't have three hearts."

jshell> System.out.print("Attention" + str.strip() + "More highlights."); Jshell > system.out.print ("Attention" + str.stripLeading() + "More highlights."); Jshell > system.out.print ("Attention" + str.stripTrailing() + "More highlights."); I don't have three heartsCopy the code

repeat(int)

The repeat method simply repeats the string multiple times in the form of an int.

jshell> String str = "Follow I Don't Have Three Hearts for more great content!".repeat(3);
str ==> "Follow" I Don't Have Three Hearts "for more highlights! Follow "I Don't Have Three Hearts" for more highlights! Follow "I Don't Have Three Hearts" for more great content!

jshell>
Copy the code

File read/write string

Java 11 aims to make strings easy to read and write. It introduces the following methods for reading and writing files:

  • readString();
  • writeString();

Here is an example of code:

Path path = Files.writeString(Files.createTempFile("test".".txt"), "This was posted on wmyskxz.com");
System.out.println(path);
String s = Files.readString(path);
System.out.println(s); //This was posted on wmyskxz.com
Copy the code

Xi. Other changes

Delete Java EE and CORBA modules (JEP 320)

These modules have been deprecated in Java 9 and are now completely removed.

The following packages were deleted: Java.xml. ws, java.xml.bind, java.xml.ws. Annotation, java.corba, Java.transaction, java.se.ee, JDK.xml. ws, jdk.xml.bind

Flight Recorder (JEP 328)

Flight Recorder, previously a commercial add-on to the Oracle JDK, is now open source because the Oracle JDK itself is no longer free.

JFR is an analysis tool for collecting diagnostic information and analysis data from running Java applications. Its performance overhead is negligible, usually less than 1%. Therefore, it can be used for production applications.

By default, JFR is disabled by the JVM and to start JFR, you must start it with the -xx :+FlightRecorder option. For example, we want to launch an application called MyApp:

Java -xx: + UnlockCommercialFeatures -xx: + FlightRecorder MyAppCopy the code

Java Fliight Recorder – juejin.cn/post/684490…

ChaCha20 and Poly1305 Encryption Algorithms (JEP 329)

Java 11 provides ChaCha20 and Chacha20-Poly1305 password implementations. These algorithms will be implemented in the SunJCE provider.

Have a detailed understanding of the needs of friends can see: mkyong.com/java/java-1…

Improved Aarch64 internal Features (JEP 315)

Improved existing string and array built-in functions, and implemented new built-in functions for sin, cos, and log functions under the java.lang.Math package on the AArch64 processor.

Deprecated Nashorn JavaScript Engine (JEP 335)

The Nashorn JavaScript scripting engine and JJS tools have been deprecated and may be removed in future releases.

Ps: Nashorn is in Java 8JEP 174To replace the Rhino Javascript engine.

Transport Layer Security (TLS) 1.3 (JEP 332)

Java 11 supports RFC 8446 Transport Layer Security (TLS) 1.3 protocol. However, not all TLS 1.3 features are implemented, refer to this JEP 332 for more information.

Java Secure Socket Extension (JSSE) + TLS 1.3 example.

import javax.net.ssl.SSLSocket;
import javax.net.ssl.SSLSocketFactory;

SSLSocketFactory factory =
        (SSLSocketFactory) SSLSocketFactory.getDefault();
socket =
        (SSLSocket) factory.createSocket("google.com".443);

socket.setEnabledProtocols(new String[]{"TLSv1.3"});
socket.setEnabledCipherSuites(new String[]{"TLS_AES_128_GCM_SHA256"});
Copy the code

Deprecating Pack200 tools and apis (JEP 336)

The Pack200 and Unpack200 tools and the Pack200 API java.util.jar in the package are not recommended by the JEP and may be removed in a future release.

(PS: Java 14JEP 367Pack200 tools and apis have been removed from.

The resources

  1. Its official instructions – openjdk.java.net/projects/jd…
  2. Java 11 the Features – www.journaldev.com/24601/java-…
  3. What is New in Java 11 – mkyong.com/java/what-i…
  4. Java 11 Nest -based Access Control | Baeldung – www.baeldung.com/java-nest-b…

The article recommended

  1. This is JDK15, JDK7 do not know? – www.wmyskxz.com/2020/08/18/…
  2. So the most fully Java version features about 8 – www.wmyskxz.com/2020/08/19/…
  3. Didn’t you know about these epic updates to Java9? – www.wmyskxz.com/2020/08/20/…
  4. You want to know about the JDK 10 version update is here – www.wmyskxz.com/2020/08/21/…
  5. “MoreThanJava” series of corpus – www.wmyskxz.com/categories/…
  • Github: More Than Java: More Than Code star: github.com/wmyskxz/Mor…
  • Personal public number: wmyskxz, personal independent domain name blog: wmyskxz.com, adhere to the original output, below the scan code concern, 2020, and you grow together!

Thank you very much for reading this, if you think this article is well written, if you think there is something about “I don’t have three hearts”, please like, follow, share and leave a comment!

Creation is not easy, your support and recognition, is the biggest motivation for my creation, we will see you in the next article!