New Features in Java 11 – Java 11的新功能

最后修改: 2021年 1月 2日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

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

甲骨文于2018年9月发布了Java 11,距离其前身10版仅6个月。

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.

Java 11是Java 8之后的第一个长期支持(LTS)版本。Oracle也在2019年1月停止支持Java8。因此,我们很多人都会升级到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.

在本教程中,我们将看一下选择Java 11 JDK的选项。然后,我们将探讨Java 11中引入的新功能、删除的功能和性能增强。

2. Oracle vs. Open JDK

2.甲骨文与开放的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.

Java 10是最后一个免费的Oracle JDK版本,我们可以在没有许可证的情况下在商业上使用。从Java 11开始,甲骨文就没有免费的长期支持(LTS)了。

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

庆幸的是,Oracle继续提供Open JDK版本,我们可以免费下载和使用。

Besides Oracle, there are other Open JDK providers that we may consider.

除了Oracle,还有其他Open JDK提供商,我们可以考虑。

3. Developer Features

3.开发者功能

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

让我们来看看通用API的变化,以及其他一些对开发者有用的功能。

3.1. New String Methods

3.1.新的字符串方法

Java 11 adds a few new methods to the String class: isBlank, lines, strip, stripLeading, stripTrailing, and repeat.

Java 11为String类添加了一些新的方法isBlanklinesstripstripLeadingstripTrailing,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.");

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

这些方法可以减少操作字符串对象时涉及的模板数量,并使我们不必导入库。

In the case of the strip methods, they provide similar functionality to the more familiar trim method; however, with finer control and Unicode support.

strip方法而言,它们提供了与更熟悉的trim方法类似的功能;但是,控制更精细,并支持Unicode。

3.2. New File Methods

3.2.新文件方法

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

此外,现在更容易从文件中读写Strings。

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

我们可以使用新的readStringwriteString静态方法,这些方法来自Files类:

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

3.3. Collection to an Array

3.3.集合到一个数组

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

java.util.Collection接口包含一个新的默认toArray方法,它需要一个IntFunction参数。

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

3.4.非谓语方法

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:

一个静态的not方法已经被添加到Predicate 界面中。我们可以用它来否定一个现有的谓词,就像negate方法一样。

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

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

虽然not(isBlank)isBlank.negate()读起来更自然,但最大的好处是,我们也可以用not与方法引用,如not(String:isBlank)..

3.5. Local-Variable Syntax for Lambda

3.5.本地变量语法 for Lambda

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

在 Java 11 中增加了对在 lambda 参数中使用本地变量语法var关键字)的支持。

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

3.6. HTTP Client

3.6.HTTP客户端

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.

来自java.net.http包的新的HTTP客户端是在Java 9中引入的。 它现在已经成为Java 11的一个标准功能。

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

新的HTTP API提高了整体性能,并提供对HTTP/1.1和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!");

3.7. Nest Based Access Control

3.7.基于鸟巢的访问控制

Java 11 introduces the notion of nestmates and the associated access rules within the JVM.

Java 11引入了nestmates的概念以及JVM中的相关访问规则。

A nest of classes in Java implies both the outer/main class and all its nested classes:

在Java中,一个类的嵌套意味着外部/主类和其所有的嵌套类。

assertThat(MainClass.class.isNestmateOf(MainClass.NestedClass.class)).isTrue();

Nested classes are linked to the NestMembers attribute, while the outer class is linked to the NestHost attribute:

嵌套类被链接到NestMembers属性,而外层类被链接到NestHost属性。

assertThat(MainClass.NestedClass.class.getNestHost()).isEqualTo(MainClass.class);

JVM access rules allow access to private members between nestmates; however, in previous Java versions, the reflection API denied the same access.

JVM的访问规则允许网友之间访问私有成员;但是,在以前的Java版本中,reflection API拒绝了同样的访问。

Java 11 fixes this issue and provides means to query the new class file attributes using the reflection API:

Java 11修复了这个问题,并提供了使用反射API查询新类文件属性的方法。

Set<String> nestedMembers = Arrays.stream(MainClass.NestedClass.class.getNestMembers())
  .map(Class::getName)
  .collect(Collectors.toSet());
assertThat(nestedMembers).contains(MainClass.class.getName(), MainClass.NestedClass.class.getName());

3.8. Running Java Files

3.8.运行Java文件

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

这个版本的一个主要变化是,我们不再需要用javac明确地编译Java源文件

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

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

相反,我们可以直接使用java命令运行该文件

$ java HelloWorld.java
Hello Java 11!

4. Performance Enhancements

4.性能增强

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

现在让我们来看看几个新功能,其主要目的是提高性能。

4.1. Dynamic Class-File Constants

4.1.Dynamic Class-File Constants

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

Java类文件格式得到扩展,以支持一种新的常量池形式,名为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.

加载新的常量池将委托创建一个引导方法,就像链接一个invokedynamic调用站点委托链接到一个引导方法一样。

This feature enhances performance and targets language designers and compiler implementors.

这一功能增强了性能,目标是语言设计者和编译器实现者。

4.2. Improved Aarch64 Intrinsics

4.2.改进的Aarch64内含物

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.

Java 11 在 ARM64 或 AArch64 处理器上优化了现有的字符串和数组本征。此外,还为sin、cos、log方法的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.

我们像其他函数一样使用内在函数;然而,内在函数被编译器以一种特殊的方式处理。它利用CPU架构特定的汇编代码来提高性能。

4.3. A No-Op Garbage Collector

4.3.一个No-Op垃圾收集器

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

一个名为Epsilon的新垃圾收集器作为实验性功能可在Java 11中使用。

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.

它被称为No-Op(无操作),因为它分配了内存,但实际上并没有收集任何垃圾。因此,Epsilon适用于模拟内存不足的错误。

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:

显然,Epsilon不适合典型的生产型Java应用;但是,在一些特定的使用场合,它可能是有用的。

  • 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.

为了启用它,使用 -XX:+UnlockExperimentalVMOptions -XX:+UseEpsilonGC标志。

4.4. Flight Recorder

4.4.飞行记录器

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.

Java Flight Recorder(JFR)现在在Open JDK中是开源的,而它曾经是Oracle JDK的商业产品。JFR是一种剖析工具,我们可以用它来收集运行中的Java应用程序的诊断和剖析数据。

To start a 120 seconds JFR recording, we can use the following parameter:

要启动120秒的JFR录音,我们可以使用以下参数。

-XX:StartFlightRecording=duration=120s,settings=profile,filename=java-demo-app.jfr

We can use JFR in production since its performance overhead is usually below 1%. Once the time elapses, we can access the recorded data saved in a JFR file; however, in order to analyze and visualize the data, we need to make use of another tool called JDK Mission Control (JMC).

我们可以在生产中使用JFR,因为其性能开销通常低于1%。一旦时间过去,我们就可以访问保存在JFR文件中的记录数据;但是,为了分析和可视化这些数据,我们需要利用另一个工具,即JDK任务控制(JMC)。

5. Removed and Deprecated Modules

5.被删除和废弃的模块

As Java evolves, we can no longer use any of its removed features and should stop using any deprecated features. Let’s take a quick look at the most notable ones.

随着Java的发展,我们不能再使用其删除的任何功能,应该停止使用任何废弃的功能。让我们快速浏览一下最值得注意的那些。

5.1. Java EE and CORBA

5.1 Java EE和CORBA

Standalone versions of the Java EE technologies are available on third-party sites; therefore, there is no need for Java SE to include them.

Java EE技术的独立版本可以在第三方网站上找到;因此,Java SE没有必要包括它们。

Java 9 already deprecated selected Java EE and CORBA modules. In release 11, it has now completely removed:

Java 9 已经废弃了选定的 Java EE 和 CORBA 模块。在第11版中,它现在已经完全删除。

  • Java API for XML-Based Web Services (java.xml.ws)
  • Java Architecture for XML Binding (java.xml.bind)
  • JavaBeans Activation Framework (java.activation)
  • Common Annotations (java.xml.ws.annotation)
  • Common Object Request Broker Architecture (java.corba)
  • JavaTransaction API (java.transaction)

5.2. JMC and JavaFX

5.2.JMC和JavaFX

JDK Mission Control (JMC) is no longer included in the JDK. A standalone version of JMC is now available as a separate download.

JDK 任务控制(JMC)不再包含在 JDK 中。JMC 的独立版本现在可以单独下载。

The same is true for JavaFX modules; JavaFX will be available as a separate set of modules outside of the JDK.

对于JavaFX模块也是如此;JavaFX将作为JDK之外的一套单独的模块提供。

5.3. Deprecated Modules

5.3.废弃的模块

Furthermore, Java 11 deprecated the following modules:

此外,Java 11废弃了以下模块。

  • Nashorn JavaScript engine, including the JJS tool
  • Pack200 compression scheme for JAR files

6. Miscellaneous Changes

6.杂项修改

Java 11 introduced a few more changes that are important to mention:

Java 11还引入了一些需要提及的变化。

  • New ChaCha20 and ChaCha20-Poly1305 cipher implementations replace the insecure RC4 stream cipher
  • Support for cryptographic key agreement with Curve25519 and Curve448 replace the existing ECDH scheme
  • Upgraded Transport Layer Security (TLS) to version 1.3 brings security and performance improvements
  • Introduced a low latency garbage collector, ZGC, as an experimental feature with low pause times
  • Support for Unicode 10 brings more characters, symbols, and emojis

7. Conclusion

7.结语

In this article, we explored some new features of Java 11.

在这篇文章中,我们探讨了Java 11的一些新特性。

We covered the differences between Oracle and Open JDK. We also reviewed API changes, as well as other useful development features, performance enhancements, and removed or deprecated modules.

我们涵盖了Oracle和Open JDK之间的差异。我们还回顾了API的变化,以及其他有用的开发特性、性能增强,以及被删除或废弃的模块。

As always, the source code is available over on GitHub.

像往常一样,源代码可在GitHub上获得