java 1.8新增功能_Java 14新增功能

java 1.8新增功能

Java 14 is going to be released on March 17, 2020. Besides ~2,400 bug fixes and small enhancements, the new version of Java contains 16 major enhancements, also called JEPs (Java Enhancement Proposals).

Java 14将于2020年3月17日发布。除了约2,400个错误修复和小的增强功能之外,Java的新版本还包含16个主要增强功能,也称为JEP(Java增强建议)。

Let’s take a closer look at the major updates in Java 14: new switch expressions, better NullPointerExceptions, improvements in garbage collection, JFR event streaming, and more.

让我们仔细看一下Java 14中的主要更新:新的开关表达式,更好的NullPointerException ,垃圾收集方面的改进,JFR事件流等等。

Image for post
Image source: Author
图片来源:作者

切换表达式 (Switch Expressions)

This update to the Java language was already available in Java 12 and 13 but only as a preview language feature, which means it was not enabled by default. Finally, the new switch expressions are released in Java 14. Making a long story short, Java 14 introduces a new simplified form of a switch block with case L -> ... labels. The new switch expressions may help to simplify code in some cases. Here are a couple of examples.

Java语言的此更新已在Java 12和13中提供,但仅作为预览语言功能提供,这意味着默认情况下未启用。 最后,新的switch表达式在Java 14中发布。总而言之,Java 14引入了带有case L -> ...标签的switch块的新简化形式。 在某些情况下,新的开关表达式可能有助于简化代码。 这里有几个例子。

Let’s assume that we have an enum that describes weekdays. We can write the following code using the new switch expressions:

假设我们有一个描述工作日的枚举。 我们可以使用新的switch表达式编写以下代码:

switch (day) {
case MONDAY -> System.out.println("Aweful");
case TUESDAY, WEDNESDAY -> System.out.println("Okay");
case THURSDAY -> System.out.println("Good");
case FRIDAY -> System.out.println("Great");
case SATURDAY, SUNDAY -> System.out.println("Awesome");
}

Here we just used a single expression for each case. Note that the switch block doesn't use any break statement, which makes it much shorter. The next example shows how the new switch expressions can return a value:

在这里,我们只为每种case使用一个表达式。 请注意, switch块不使用任何break语句,这使其更短。 下一个示例显示新的开关表达式如何返回值:

int numLetters = switch (day) {
case MONDAY, FRIDAY, SUNDAY -> 6;
case TUESDAY -> 7;
case THURSDAY, SATURDAY -> 8;
case WEDNESDAY -> 9;
};

It’s also possible to write multi-line blocks and return a value with a new keyword yield:

也可以编写多行块并返回带有新关键字yield的值:

int result = switch (s) {
case "Foo" -> 1;
case "Bar" -> 2;
default -> {
System.out.println("Neither Foo nor Bar, hmmm...");
yield 0;
}
};

There are several important things that you need to keep in mind when you use the new switch expressions. For example, the cases of new switch expressions have to be exhaustive. It means that, for all possible values, there has to be a matching switch label. Or, since yield is now a keyword, a class with a name yield now becomes illegal in Java 14.

使用新的switch表达式时,需要牢记一些重要的事情。 例如,新开关表达式的情况必须详尽无遗。 这意味着,对于所有可能的值,必须有一个匹配的开关标签。 或者,由于yield现在是关键字,因此具有名称yield的类现在在Java 14中变得非法。

If you'd like to learn more about the new switch expressions, you're welcome to read JEP 361. The authors provided quite a lot of useful info about the new switch expressions.

如果您想了解有关新开关表达式的更多信息,欢迎阅读JEP 361 。 作者提供了许多有关新开关表达式的有用信息。

有用的NullPointerExceptions (Helpful NullPointerExceptions)

The JVM throws a NullPointerException (NPE) when code tries to dereference a null reference. All Java developers have seen them before. For example, the following code may result in an NPE:

当代码尝试取消引用空引用时,JVM抛出NullPointerException (NPE)。 所有Java开发人员以前都看过它们。 例如,以下代码可能会导致NPE:

foo.bar = 10;

The NPE is going to look like the following:

NPE将如下所示:

Exception in thread "main" java.lang.NullPointerException
at App.main(App.java:17)

The exception message contains a filename and a line where the null dereference happened. For the foo.bar = 10; statement, it's not too difficult to figure out that the NPE was thrown because the foo variable was null. Unfortunately, sometimes it’s not clear what exactly causes an NPE. For example, if either a, b or c is null, then an NPE is going to be thrown:

异常消息包含文件名和发生空解除引用的行。 对于foo.bar = 10; 语句,因为foo变量为null,所以抛出NPE并不是很困难。 不幸的是,有时不清楚是什么导致了NPE。 例如,如果abc为空,则将引发NPE:

a.b.c.d = 42;

However, no matter which field was null, the NPE is going to look the same. It doesn’t give any clue which field was actually null.

但是,无论哪个字段为空,NPE都将看起来相同。 它没有任何线索表明哪个字段实际上为空。

Here is another example. If one of the nested arrays is null, it results in an NPE:

这是另一个例子。 如果嵌套数组之一为null,则将导致NPE:

a[i][j][k] = 99;

Again, no matter which array was null, the NPE is going to look the same.

同样,无论哪个数组为空,NPE都将看起来相同。

Java 14 addresses this problem and makes NPEs more friendly. Now the JVM can figure out which variable was null, and then it lets the user know about it in the exception message. For example, a null dereference in the line foo.bar = 10; is going to result in the following NPE:

Java 14解决了此问题并使NPE更友好。 现在,JVM可以找出哪个变量为null,然后在异常消息中让用户知道它。 例如, foo.bar = 10;行中的空取消引用foo.bar = 10; 将导致以下NPE:

Exception in thread "main" java.lang.NullPointerException: 
Cannot assign field "bar" because "foo" is null
at App.main(App.java:17)

A null dereference in the line a.b.c.d = 41; is going to result in the following NPE if a.b was null:

abcd = 41;中的空取消引用abcd = 41; 如果ab为null,将导致以下NPE:

Exception in thread "main" java.lang.NullPointerException: 
Cannot read field "c" because "a.b" is null
at App.main(App.java:17)

The new info in NullPointerExceptions may be very helpful in analyzing its root cause and can make the developer’s life a bit easier. By the way, the improvement has been available in SAP’s JVM since 2006. Unfortunately, it took 14 years to finally bring it into OpenJDK.

NullPointerException的新信息对于分析其根本原因可能非常有帮助,并且可以使开发人员的生活更加轻松。 顺便说一句,自2006年以来,SAP的JVM中就已经进行了改进。不幸的是,最终将其引入OpenJDK花费了14年的时间。

If you’re interested in the details, the authors of the JEP 358 provided a lot of info about the new feature.

如果您对这些细节感兴趣, JEP 358的作者提供了有关此新功能的大量信息。

包装工具(培养箱) (Packaging Tool (Incubator))

Currently, a Java application is usually distributed as a simple JAR file. However, it’s not very convenient, especially for a user of the application. It would be much better if the Java application were an installable package like MSI on Windows or DMG on Mac. This would allow Java applications to be distributed, installed, and uninstalled in a way that is familiar to users.

当前,Java应用程序通常以简单的JAR文件的形式分发。 但是,这不是很方便,特别是对于应用程序的用户而言。 如果Java应用程序是可安装的软件包,例如Windows上的MSI或Mac上的DMG,那就更好了。 这将允许Java应用程序以用户熟悉的方式进行分发,安装和卸载。

JEP 343 introduces the jpackage tool, which packages a Java application into a platform-specific package that includes all of the necessary dependencies. Here’s a list of supported package formats:

JEP 343引入了jpackage工具,该工具将Java应用程序打包到特定于平台的程序包中,该程序包包含所有必需的依赖项。 以下是受支持的软件包格式的列表:

  • DEB and RPM on Linux

    Linux上的DEB和RPM
  • PKG and DMG on macOS

    Mac OS上的PKG和DMG
  • MSI and EXE on Windows

    Windows上的MSI和EXE

Here is an example of how the new tool can be used:

以下是如何使用新工具的示例:

$ jpackage --name myapp --input lib --main-jar main.jar \
--main-class myapp.Main

It takes the lib/main.jar file and produces a package in the format most appropriate for the system on which it is run. The entry point is the myapp.Main class.

它获取lib/main.jar文件,并以最适合其运行系统的格式生成一个软件包。 入口点是myapp.Main类。

The JEP’s authors provided quite a lot of useful information about the new tool.

JEP的作者提供了很多有关新工具的有用信息

Although the jpackage tool is available in JDK 14, it's delivered as an incubator module, which means that the functionality is not guaranteed to be stable and may be revised in a future release.

尽管JDK 14中提供了jpackage工具,但它是作为孵化器模块提供的,这意味着该功能不能保证稳定,并且可能在将来的版本中进行修改。

更好的垃​​圾收集 (Better Garbage Collection)

Java 14 contains multiple enhancements in garbage collection.

Java 14在垃圾回收方面包含多项增强功能。

JEP 345 improves the G1 garbage collector by implementing NUMA-aware memory allocation. By the way, NUMA stands for Non-Uniform Memory Access. This feature has been implemented in the parallel garbage collector for a long time. Now it can be enabled in the G1 as well by running Java with a new +XX:+UseNUMA command-line option. This should improve G1 performance on large machines.

JEP 345通过实现可识别NUMA的内存分配来改进G1垃圾收集器。 顺便说一下,NUMA代表非统一内存访问。 此功能已在并行垃圾收集器中实现很长时间了。 现在,可以通过使用新的+XX:+UseNUMA命令行选项运行Java来在G1中启用它。 这将改善大型计算机上的G1性能。

JEP 363 removes the Concurrent Mark Sweep (CMS) garbage collector which was deprecated a couple of years ago. Goodbye CMS!

JEP 363删除了几年前已弃用的并发标记扫描(CMS)垃圾收集器。 再见CMS!

JEP 364 and JEP 365 make the Z garbage collector (ZGC) available on macOS and Windows. ZGC is a concurrent garbage collector that was added to the JVM a couple of years ago. ZGC tries to reduce pause times for garbage collections and can handle heaps of size ranging from a few hundred megabytes to multi-terabytes. Previously, the collector could run only on Linux. JEP 366 deprecates the combination of the Parallel Scavenge and Serial Old garbage collection algorithms. This combination had to be enabled by the user with the -XX:+UseParallelGC -XX:-UseParallelOldGC command-line options. The authors believe that the combination is uncommon but requires a significant amount of maintenance effort. In fact, the option -XX:UseParallelOldGC is now deprecated. A warring is going to be displayed if the deprecated modes are used.

JEP 364JEP 365使Z垃圾收集器(ZGC)在macOS和Windows上可用。 ZGC是并发垃圾收集器,几年前添加到JVM中。 ZGC试图减少垃圾收集的暂停时间,并且可以处理大小从几百兆字节到几兆字节不等的堆。 以前,收集器只能在Linux上运行。 JEP 366不赞成使用Parallel Scavenge和Serial Old垃圾收集算法的组合。 用户必须使用-XX:+UseParallelGC -XX:-UseParallelOldGC命令行选项启用此组合。 作者认为,这种组合并不常见,但需要大量的维护工作。 实际上,选项-XX:UseParallelOldGC现在已被弃用。 如果使用了过时的模式,将显示一个warring。

JFR事件流 (JFR Event Streaming)

JDK Flight Recorder (JFR) is an event recorder that is built into the JVM. It captures diagnostic and profiling data about the JVM itself, and the application running in the JVM. JFR used to be a proprietary tool, but it was open-sourced in 2018 Java released as part of OpenJDK 11.

JDK Flight Recorder(JFR)是JVM中内置的事件记录器。 它捕获有关JVM本身以及JVM中运行的应用程序的诊断和分析数据。 JFR曾经是专有工具,但它在2018年开源,作为OpenJDK 11的一部分发布的Java。

To consume the data provided by JFR, a user has to start a recording, stop it, dump the contents to disk, and then parse the recording file. This works quite well for application profiling but not for monitoring purposes.

要使用JFR提供的数据,用户必须开始记录,停止记录,将内容转储到磁盘,然后解析记录文件。 这对于应用程序概要分析非常有效,但不适用于监视目的。

In Java 14, the JFR allows users to subscribe to events asynchronously. Users can now register a handler that’s going to be invoked in response to the arrival of an event. The RecordingStream class provides a uniform way to filter and consume events. Here is an example provided by the JEP's authors:

在Java 14中,JFR允许用户异步订阅事件。 用户现在可以注册一个处理程序,该处理程序将响应事件的到来而被调用。 RecordingStream类提供了一种统一的方法来过滤和使用事件。 这是JEP作者提供的示例:

More info can be found in JEP 349.

可以在JEP 349中找到更多信息。

语言预览功能 (Language preview features)

Java 14 contains several updates to the Java language with are not yet available by default.

Java 14包含对Java语言的若干更新,默认情况下尚不可用。

First, JEP 305 extends the instanceof operator with a binding variable. Here is an example:

首先, JEP 305使用绑定变量扩展instanceof运算符。 这是一个例子:

if (obj instanceof String s) {
// can use s here
}

If obj is an instance of String, then it is cast to String and assigned to the binding variable s.

如果objString的实例,则将其强制转换为String并分配给绑定变量s

Second, JEP 359 introduces records to the Java language. A record has a name and a state description. The state description declares the components of the record. A record may also have a body. Here is a short example:

其次, JEP 359将记录引入Java语言。 记录具有名称和状态描述。 状态描述声明记录的组成部分。 唱片也可能有身体。 这是一个简短的示例:

record Point(int x, int y) {}

Third, after collecting feedback for Java 13, JEP 368 adds a couple of new escape sequences for the text blocks that were previously introduced in Java 13 as a language preview feature.

第三,在收集了针对Java 13的反馈之后, JEP 368为先前在Java 13中作为语言预览功能引入的文本块添加了两个新的转义序列。

Unfortunately, these three updates are still only available as preview language features that are not enabled by default. To enable the new syntax, you’ll have to run the Java compiler with --enable-preview --release 14 options and then launch java with --enable-preview option:

不幸的是,这三个更新仍仅作为预览语言功能提供,默认情况下未启用。 要启用新语法,您必须使用--enable-preview --release 14选项运行Java编译器,然后使用--enable-preview选项启动java

$ javac -d classes --enable-preview --release 14 Test.java
$ java -classpath classes --enable-preview Test

其余的部分 (The Rest)

What else has changed in Java 14?

Java 14还有哪些其他变化?

JEP 370 introduces an API to allow Java applications to safely and efficiently access foreign memory outside of the Java heap. Sounds scary. The new API should become an alternative to the java.nio.ByteBuffer and sun.misc.Unsafe classes. This feature is provided as an incubating module.

JEP 370引入了一个API,以允许Java应用程序安全有效地访问Java堆外部的外部内存。 听起来很吓人。 新的API应该成为java.nio.ByteBuffersun.misc.Unsafe类的替代方法。 此功能作为孵化模块提供。

JEP 352 adds new file mapping modes so that the FileChannel API can be used to create MappedByteBuffer instances that refer to non-volatile memory (NVM).

JEP 352添加了新的文件映射模式,以便可以使用FileChannel API创建引用非易失性存储器(NVM)的MappedByteBuffer实例。

The Pack200 tool was deprecated in Java 11. Now JEP 367 removed the tool and its API.

在Java 11中不推荐使用Pack200工具。现在, JEP 367删除了该工具及其API。

In case you know about Solaris and SPARC, JEP 362 drops support for the Solaris/SPARC, Solaris/x64, and Linux/SPARC platforms. In the future, the ports on these platforms most likely are going to be removed from OpenJDK.

如果您了解Solaris和SPARC, JEP 362将放弃对Solaris / SPARC,Solaris / x64和Linux / SPARC平台的支持。 将来,这些平台上的端口很可能将从OpenJDK中删除。

结论 (Conclusion)

Compared to the five JEPs in Java 13, the new Java 14 delivers many more major enhancements. The updates touch various areas. Most likely, the most interesting updates for Java developers are going to be the new switch expressions and the enhanced NullPointerExceptions. Don’t forget to try out the new language preview features and provide your feedback to the JDK developers. Enjoy the new Java 14!

与Java 13中的五个JEP相比,新的Java 14提供了更多的主要增强功能。 更新涉及各个领域。 对于Java开发人员而言,最可能最有趣的更新将是新的switch表达式和增强的NullPointerException 。 不要忘记尝试新的语言预览功能,并将您的反馈提供给JDK开发人员。 享受新的Java 14!

翻译自: https://medium.com/better-programming/whats-new-in-java-14-a472ec291c05

java 1.8新增功能

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值