New features in Java 18

Java language feature series

sequence

This article mainly describes the new features of Java 18

version number

java -version
openjdk version "18" 2022-03-22
OpenJDK Runtime Environment (build 18+36-2087)
OpenJDK 64-Bit Server VM (build 18+36-2087, mixed mode, sharing)
复制代码

It can be seen from the version information that it is build 18+36

Feature list

JEP 400: UTF-8 by Default

Before java18, Charset.defaultCharset() was determined according to the operating system, user locale, etc., resulting in different default charsets for different operating systems. This time the unified change to UTF-8 java18 needs -Dfile.encoding=UTF-8to be set to UTF-8. If you still want to use the previous judgment method, you can -Dfile.encoding=COMPATset it by

JEP 408: Simple Web Server

python -m SimpleHTTPServer [port]Provides an out-of-the-box HTTP file server similar to Python's SimpleHTTPServer( ) that can be jwebserver -p 9000started by

jwebserver -p 9000
Binding to loopback by default. For all interfaces use "-b 0.0.0.0" or "-b ::".
Serving /tmp and subdirectories on 127.0.0.1 port 9000
URL http://127.0.0.1:9000/
复制代码

It can also be customized and started in the code

jshell> var server = SimpleFileServer.createFileServer(new InetSocketAddress(8080),
   ...> Path.of("/some/path"), OutputLevel.VERBOSE);
jshell> server.start()
复制代码

JEP 413: Code Snippets in Java API Documentation

In the past, to show code through javadoc, you can use @code as follows

<pre>{@code
    lines of source code
}</pre>
复制代码

But its disadvantage is that it has to be wrapped with pre, resulting in that the fragment cannot contain html tags, and the indentation is not very flexible

This time, the @snippet tag is introduced to javaDoc, so there is no need to escape the html tag.

/**
 * The following code shows how to use {@code Optional.isPresent}:
 * {@snippet :
 * if (v.isPresent()) {
 *     System.out.println("v: " + v.get());
 * }
 * }
 */
复制代码

You can also directly refer to the source code to avoid the disconnection between the javadoc code and the actual code

/**
 * The following code shows how to use {@code Optional.isPresent}:
 * {@snippet file="ShowOptional.java" region="example"}
 */
复制代码

JEP 416: Reimplement Core Reflection with Method Handles

通过Method Handles重新实现java.lang.reflect.Method, Constructor及Field来替代字节码生成的Method::invoke, Constructor::newInstance, Field::get, and Field::set的实现 方便支持Project Valhalla,为以后减少扩展成本

JEP 417: Vector API (Third Incubator)

JDK16引入了JEP 338: Vector API (Incubator)提供了jdk.incubator.vector来用于矢量计算 JDK17进行改进并作为第二轮的incubatorJEP 414: Vector API (Second Incubator) JDK18进行改进并作为第三轮的incubator

JEP 418: Internet-Address Resolution SPI

给解析网络地址提供了SPI,即java.net.spi包的InetAddressResolverProvider 方便给project loom做准备(目前InetAddress的API会阻塞在系统调用),也方便定制化及testing

JEP 419: Foreign Function & Memory API (Second Incubator)

JDK14的JEP 370: Foreign-Memory Access API (Incubator)引入了Foreign-Memory Access API作为incubator JDK15的JEP 383: Foreign-Memory Access API (Second Incubator)Foreign-Memory Access API作为第二轮incubator JDK16的JEP 393: Foreign-Memory Access API (Third Incubator)作为第三轮,它引入了Foreign Linker API JDK17引入JEP 412: Foreign Function & Memory API (Incubator)作为第一轮incubator JDK18则作为第二轮的incubator

JEP 420: Pattern Matching for switch (Second Preview)

instanceof的模式匹配在JDK14作为preview,在JDK15作为第二轮的preview,在JDK16转正

static String formatterPatternSwitch(Object o) {
    return switch (o) {
        case Integer i -> String.format("int %d", i);
        case Long l    -> String.format("long %d", l);
        case Double d  -> String.format("double %f", d);
        case String s  -> String.format("String %s", s);
        default        -> o.toString();
    };
}
复制代码

JDK17引入JEP 406: Pattern Matching for switch (Preview) JDK18则作为第二轮的preview

JEP 421: Deprecate Finalization for Removal

废弃finalize方法方便后续移除

细项解读

上面列出的是大方面的特性,除此之外还有一些api的更新及废弃,主要见JDK 18 Release Notes,这里举几个例子。

添加项

  • SerialGC、ParallelGC、ZGC支持String Deduplication

可使用-XX:+UseStringDeduplication开启

  • Map from an Element to its JavaFileObject

新增Elements.getFileObjectOf(Element)来映射为JavaFileObject

可以使用-XX:GCCardSizeInBytes来设置card table大小

允许G1的heap regions的最大值从之前的32MB到512MB

  • JDK Flight Recorder Event for FinalizationJDK-8266936

新增jdk.FinalizerStatistics

移除项

  • Removal of Google's GlobalSign Root CertificateJDK-8225083

移除了google的GlobalSign根证书

  • Removal of Empty finalize() Methods in java.desktop ModuleJDK-8273102

移除java.desktop模块里头的空finalize()方法

  • Removal of impl.prefix JDK System Property Usage From InetAddressJDK-8274227

移除impl.prefix属性,转而使用InetAddressResolver这个spi

  • Removal of Support for Pre JDK 1.4 DatagramSocketImpl ImplementationsJDK-8260428

移除jdk1.4之前的DatagramSocketImpl

  • Removal of Legacy PlainSocketImpl and PlainDatagramSocketImpl ImplementationsJDK-8253119

移除java.net.SocketImpl及java.net.DatagramSocketImpl的老实现PlainSocketImpl、PlainDatagramSocketImpl jdk.net.usePlainDatagramSocketImpl属性也一并移除

废弃项

完整列表见deprecated-list

废弃javax.security.auth.Subject::doAs为移除做准备

  • Deprecated sun.misc.Unsafe Methods That Return OffsetsJDK-8277863

sun.misc.Unsafe中objectFieldOffset, staticFieldOffset, staticFieldBase方法被废弃

废弃Thread.stop为后续移除做准备

  • Obsoleted Product Options -XX:G1RSetRegionEntries and -XX:G1RSetSparseRegionEntriesJDK-8017163

废弃-XX:G1RSetRegionEntries-XX:G1RSetSparseRegionEntries

已知问题

  • Extended Delay Before JDK Executable Installer Starts From Network DriveJDK-8274002

在 Windows 11 和 Windows Server 2022 上,从映射的网络驱动器启动时,临时安装文件的提取可能会有些缓慢。安装程序仍然可以工作,但可能会有暂时的延迟。

小结

Java18主要有如下几个特性

doc

Guess you like

Origin juejin.im/post/7078301679992438797