New Features in Java 11

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

1. Overview

Oracle released Java 11 in September 2018, only 6 months after its predecessor, version 10.

Java 11 is the first long-term support (LTS) release after Java 8. Oracle also stopped supporting Java 8 in January 2019. As a consequence, a lot of us will upgrade to Java 11.

In this tutorial, we'll take a look at our options for choosing a Java 11 JDK. Then we'll explore new features, removed features, and performance enhancements introduced in Java 11.

2. Oracle vs. Open JDK

Java 10 was the last free Oracle JDK release that we could use commercially without a license. Starting with Java 11, there's no free long-term support (LTS) from Oracle.

Thankfully, Oracle continues to provide Open JDK releases, which we can download and use without charge.

3. Developer Features

Let's take a look at changes to the common APIs, as well as a few other features useful for developers.

3.1. New String Methods

Java 11 adds a few new methods to the String classisBlanklinesstripstripLeadingstripTrailing, and repeat.

Let's see how we can make use of the new methods to extract non-blank, stripped lines from a multi-line string:

String multilineString = "Baeldung helps \n \n developers \n explore Java.";
List<String> lines = multilineString.lines()
  .filter(line -> !line.isBlank())
  .map(String::strip)
  .collect(Collectors.toList());
assertThat(lines).containsExactly("Baeldung helps", "developers", "explore Java.");Copy

These methods can reduce the amount of boilerplate involved in manipulating string objects, and save us from having to import libraries.

3.2. New File Methods

Additionally, it's now easier to read and write Strings from files.

We can use the new readString and writeString static methods from the Files class:

Path filePath = Files.writeString(Files.createTempFile(tempDir, "demo", ".txt"), "Sample text");
String fileContent = Files.readString(filePath);
assertThat(fileContent).isEqualTo("Sample text");Copy

3.3. Collection to an Array

The java.util.Collection interface contains a new default toArray method which takes an IntFunction argument.

This makes it easier to create an array of the right type from a collection:

List sampleList = Arrays.asList("Java", "Kotlin");
String[] sampleArray = sampleList.toArray(String[]::new);
assertThat(sampleArray).containsExactly("Java", "Kotlin");

3.4. The Not Predicate Method

A static not method has been added to the Predicate interface. We can use it to negate an existing predicate, much like the negate method:

List<String> sampleList = Arrays.asList("Java", "\n \n", "Kotlin", " ");
List withoutBlanks = sampleList.stream()
  .filter(Predicate.not(String::isBlank))
  .collect(Collectors.toList());
assertThat(withoutBlanks).containsExactly("Java", "Kotlin");Copy

While not(isBlank) reads more naturally than isBlank.negate(), the big advantage is that we can also use not with method references, like not(String:isBlank).

3.5. Local-Variable Syntax for Lambda

Support for using the local variable syntax (var keyword) in lambda parameters was added in Java 11.

We can make use of this feature to apply modifiers to our local variables, like defining a type annotation:

List<String> sampleList = Arrays.asList("Java", "Kotlin");
String resultString = sampleList.stream()
  .map((@Nonnull var x) -> x.toUpperCase())
  .collect(Collectors.joining(", "));
assertThat(resultString).isEqualTo("JAVA, KOTLIN");Copy

3.6. HTTP Client

The new HTTP client from the java.net.http package was introduced in Java 9. It has now become a standard feature in Java 11.

The new HTTP API improves overall performance and provides support for both HTTP/1.1 and HTTP/2:

HttpClient httpClient = HttpClient.newBuilder()
  .version(HttpClient.Version.HTTP_2)
  .connectTimeout(Duration.ofSeconds(20))
  .build();
HttpRequest httpRequest = HttpRequest.newBuilder()
  .GET()
  .uri(URI.create("http://localhost:" + port))
  .build();
HttpResponse httpResponse = httpClient.send(httpRequest, HttpResponse.BodyHandlers.ofString());
assertThat(httpResponse.body()).isEqualTo("Hello from the server!");Copy

3.7. Nest Based Access Control

3.8. Running Java Files

A major change in this version is that we don't need to compile the Java source files with javac explicitly anymore:

$ javac HelloWorld.java
$ java HelloWorld 
Hello Java 8!Copy

Instead, we can directly run the file using the java command:

$ java HelloWorld.java
Hello Java 11!Copy

4. Performance Enhancements

Now let's take a look at a couple of new features whose main purpose is improving performance.

4.1. Dynamic Class-File Constants

Java class-file format is extended to support a new constant-pool form named CONSTANT_Dynamic.

Loading the new constant-pool will delegate creation to a bootstrap method, just as linking an invokedynamic call site delegates linkage to a bootstrap method.

4.2. Improved Aarch64 Intrinsics

Java 11 optimizes the existing string and array intrinsics on ARM64 or AArch64 processors. Additionally, new intrinsics are implemented for sin, cos, and log methods of java.lang.Math.

We use an intrinsic function like any other; however, the intrinsic function gets handled in a special way by the compiler. It leverages CPU architecture-specific assembly code to boost performance.

4.3. A No-Op Garbage Collector

A new garbage collector called Epsilon is available for use in Java 11 as an experimental feature.

It's called a No-Op (no operations) because it allocates memory but does not actually collect any garbage. Thus, Epsilon is applicable for simulating out of memory errors.

Obviously Epsilon won't be suitable for a typical production Java application; however, there are a few specific use-cases where it could be useful:

  • Performance testing
  • Memory pressure testing
  • VM interface testing and
  • Extremely short-lived jobs

In order to enable it, use the -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC flag.

4.4. Flight Recorder

Java Flight Recorder (JFR) is now open-source in Open JDK, whereas it used to be a commercial product in Oracle JDK. JFR is a profiling tool that we can use to gather diagnostics and profiling data from a running Java application.

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6
标签: Java