The JDK-21 is there, bringing virtual threads (back) into JVM as a generally available feature (if you are old enough like myself, you might have remembered that in Java 2 releases prior to 1.3 the JVM used its own threads library, known as green threads, to implement threads in the Java platform). This is big, but what else is coming?
JEP-431: Sequenced Collections: introduces new interfaces to represent collections with a defined encounter order. Each such collection has a well-defined first element, second element, and so forth, up to the last element. It also provides uniform APIs for accessing its first and last elements, and for processing its elements in reverse order.
The following new interfaces have been introduced (and retrofitted into the existing collections type hierarchy), potentially a breaking change for some library implementors:
JEP-439: Generational ZGC: improves application performance by extending the Z Garbage Collector (ZGC) to maintain separate generations for young and old objects. This will allow ZGC to collect young objects — which tend to die young — more frequently.
By default, the
-XX:+UseZGC
command-line option selects non-generational ZGC, but to select the Generational ZGC, additional command line option-XX:+ZGenerational
is required:$ java -XX:+UseZGC -XX:+ZGenerational ...
JEP-440: Record Patterns: enhances the Java programming language with record patterns to deconstruct record values. Record patterns and type patterns can be nested to enable a powerful, declarative, and composable form of data navigation and processing. This is certainly a huge step towards having a powerful, feature-rich pattern matching capabilities in the language:
interface Host {} record TcpHost(String name, int port) implements Host {} record HttpHost(String scheme, String name, int port) implements Host {}
The are several places the records could be deconstructed,
instanceof
check being one of those:final Host host = new HttpHost("https", "localhost", 8080); if (host instanceof HttpHost(var scheme, var name, var port)) { ... } else if (host instanceof TcpHost(var name, var port)) { ... }
JEP-441: Pattern Matching for switch: enhances the Java programming language with pattern matching for
switch
expressions and statements. Extending pattern matching to switch allows an expression to be tested against a number of patterns, each with a specific action, so that complex data-oriented queries can be expressed concisely and safely.Considering the example with the records deconstruction from above, we could use record patterns in
switch
expressions too:var hostname = switch(host) { case HttpHost(var scheme, var name, var port) -> name; case TcpHost(var name, var port) -> name; default -> throw new IllegalArgumentException("Unknown host"); };
But the
switch
patterns are much more powerful, with guards to pattern case labels,null
labels, etc.final Object obj = ... ; var o = switch (obj) { case null -> ... ; case String s -> ... ; case String[] a when a.length == 0 -> ... ; case String[] a -> ... ; default -> ... ; }
JEP-444: Virtual Threads: introduces virtual threads to the Java Platform. Virtual threads are lightweight threads that dramatically reduce the effort of writing, maintaining, and observing high-throughput concurrent applications. The virtual threads and executors could be used along the traditional ones, following the same familiar API:
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { executor.submit(() -> { ... }); }
Some of the quirks of the virtual threads we have discussed previously here and here, but there is one more: you could use them in parallel streams, but should you? The answer is a bit complicated, so referring you to Virtual Threads and Parallel Streams article if you are looking for clarity.
The JDK tooling (like
jcmd
andjfr
) has been updated to include the information about virtual threads where applicable.The
jcmd
thread dump lists virtual threads that are blocked in network I/O operations and virtual threads that are created by the ExecutorService interface. It does not include object addresses, locks, JNI statistics, heap statistics, and other information that appears in traditional thread dumps (as per Viewing Virtual Threads in jcmd Thread Dumps).Java Flight Recorder (JFR) can emit these events related to virtual threads (as per Java Flight Recorder Events for Virtual Threads):
jdk.VirtualThreadStart
andjdk.VirtualThreadEnd
(disabled by default)jdk.VirtualThreadPinned
(enabled by default with a threshold of 20 ms)jdk.VirtualThreadSubmitFailed
(enabled by default)
It is worth noting that Oracle has published a comprehesive guide on virtual threads as par of JDK-21 documentation update.
JEP-449: Deprecate the Windows 32-bit x86 Port for Removal: deprecates the Windows 32-bit x86 port, with the intent to remove it in a future release.
JEP-451: Prepare to Disallow the Dynamic Loading of Agents: issues warnings when agents are loaded dynamically into a running JVM. These warnings aim to prepare users for a future release which disallows the dynamic loading of agents by default in order to improve integrity by default. Serviceability tools that load agents at startup will not cause warnings to be issued in any release.
Running with
-XX:+EnableDynamicAgentLoading
on the command line serves as an explicit "opt-in" that allows agent code to be loaded into a running VM and thus suppresses the warning. Running with-XX:-EnableDynamicAgentLoading
disallows agent code from being loaded into a running VM and can be used to test possible future behavior.In addition, the system property
jdk.instrument.traceUsage
can be used to trace uses of thejava.lang.instrument
API. Running with-Djdk.instrument.traceUsage
or-Djdk.instrument.traceUsage=true
causes usages of the API to print a trace message and stack trace. This can be used to identify agents that are dynamically loaded instead of being started on the command line with-javaagent
.JEP-452: Key Encapsulation Mechanism API: introduces an API for key encapsulation mechanisms (KEMs), an encryption technique for securing symmetric keys using public key cryptography. The new APIs are centered around javax.crypto.KEM and javax.crypto.KEMSpi abstractions.
JEP-430: String Templates (Preview): enhances the Java programming language with string templates. String templates complement Java's existing string literals and text blocks by coupling literal text with embedded expressions and template processors to produce specialized results. This is a preview language feature and API.
JEP-453: Structured Concurrency (Preview): simplifies concurrent programming by introducing an API for structured concurrency. Structured concurrency treats groups of related tasks running in different threads as a single unit of work, thereby streamlining error handling and cancellation, improving reliability, and enhancing observability. This is a preview language feature and API.
JEP-443: Unnamed Patterns and Variables (Preview): enhances the Java language with unnamed patterns, which match a record component without stating the component's name or type, and unnamed variables, which can be initialized but not used. Both are denoted by an underscore character,
_
. This is a preview language feature.JEP-445: Unnamed Classes and Instance Main Methods (Preview): evolves the Java language so that students can write their first programs without needing to understand language features designed for large programs. Far from using a separate dialect of Java, students can write streamlined declarations for single-class programs and then seamlessly expand their programs to use more advanced features as their skills grow. This is a preview language feature.
JEP-446: Scoped Values (Preview): introduces scoped values, values that may be safely and efficiently shared to methods without using method parameters. They are preferred to thread-local variables, especially when using large numbers of virtual threads. This is a preview language API.
In effect, a scoped value is an implicit method parameter. It is "as if" every method in a sequence of calls has an additional, invisible, parameter. None of the methods declare this parameter and only the methods that have access to the scoped value object can access its value (the data). Scoped values make it possible to pass data securely from a caller to a faraway callee through a sequence of intermediate methods that do not declare a parameter for the data and have no access to the data.
JEP-442: Foreign Function & Memory API (3rd Preview): introduces an API by which Java programs can interoperate with code and data outside of the Java runtime. By efficiently invoking foreign functions (i.e., code outside the JVM), and by safely accessing foreign memory (i.e., memory not managed by the JVM), the API enables Java programs to call native libraries and process native data without the brittleness and danger of JNI. This is a preview language API.
JEP-448: Vector API (6th Incubator): introduces an API to express vector computations that reliably compile at runtime to optimal vector instructions on supported CPU architectures, thus achieving performance superior to equivalent scalar computations.
Those JEPs are the themes of JDK-21 but what other features are coming? There are quite a few to unpack to be fair.
JDK-8296344: Remove Dependency on G1 for Writing the CDS Archive Heap: in previous JDKs, the dumping of the CDS archive heap has complex interactions with G1, however in JDK-21 those have been removed. That also makes it possible to dump the archive heap with non-G1 collectors.
JDK-8298048: Combine CDS Archive Heap into a Single Block: combines all objects in the CDS archive heap into a single, contiguous block.
JDK-8296263: Uniform APIs for Using Archived Heap Regions: replaces two different mechanisms that existed for using archived heap regions stored in a CDS archive with unified one to be used for all GC policies.
JDK-8298966: Deprecate JMX Subject Delegation and the method JMXConnector.getMBeanServerConnection(Subject) for removal: deprecates the Java Management Extension (JMX) Subject Delegation feature for removal in a future release. The feature is enabled by the method getMBeanServerConnection(javax.security.auth.Subject) of the JMXConnector class which will be deprecated for removal.
JDK-8311073: Note if implicit annotation processing is being used: by default, the long-standing policy is that annotation processing is implicitly enabled. As that policy may change in the future, the users should get some notice they are relying on implicit processing.
JDK-8303530: Redefine JAXP Configuration File: provides the way to specify the properties file to be used by JAXP factories during the initialization outside of the JDK by specifying
jdk.xml.config.file
system property.JDK-8306703: JFR: Summary views: provides means to visualize aggregated event data from the shell. There are 70 predefined views, such as hot-methods, gc-pauses, pinned-threads, allocation-by-site, gc, memory-leaks-by-class, and more. A list of available views can be found through using
jcmd <pid> JFR.view
orjfr view <recoding>
commands, for example:jcmd <pid> JFR.view allocation-by-site jcmd <pid> JFR.view hot-methods jcmd <pid> JFR.view jcmd <pid> JFR.view maxage=1h maxsize=2000MB gc-pauses jcmd <pid> JFR.view cell-height=3 truncate=beginning width=80 system-processes jfr view --cell-height 2 FreeMemory <recoding> jfr view --verbose gc <recoding>
JDK-8267140: Support closing the HttpClient by making it auto-closable: the HttpClient now implements AutoCloseable and has been enriched with following new methods:
JDK-8306560: Add TOOLING.jsh load file: adds TOOLING.jsh load file to have better and built-in access for tools shipping with the JDK and their command-line interface. This is truly a gem since it is now possible to run tools provided by the Java Development Kit (JDK) in a JShell session (see please Running JDK Tools within a JShell Session for background).
$ jshell TOOLING | Welcome to JShell -- Version 21 | For an introduction type: /help intro jshell> interface Empty {} jshell> javap(Empty.class)
The list of available tools could be fetched using
tools()
method.jshell> tools() jar javac javadoc javap jdeps jlink jmod jpackage
JDK-8015831: Add lint check for calling overridable methods from a constructor: this one was certainly on my wish list for a long time, the
javac
may issue a warning (new lint warning categorythis-escape
) when detects the calling of the overridable methods in constructors (please check OpenJDK 21 Compiler Warning on Constructor Calling Overridable Methods for more details and excellent examples).JDK-8307466: java.time.Instant calculation bug in until and between methods: fixes the implementation of java.time.Instant.until(Temporal endExclusive, TemporalUnit unit) in some cases did not correctly borrow or carry from the nanos to the seconds when computing using
ChronoUnit.MILLIS
orChronoUnit.MICROS
.JDK-8027682: javac wrongly accepts semicolons in package and import decls: disallow extra semicolons between
import
statements, for exampleimport java.util.Map;;;; import java.util.Set;
will now generate a compiler error (but for backward compatibility, when compiling source versions prior to
21
, a warning is generated instead of an error).JDK-8026369: javac potentially ambiguous overload warning needs an improved scheme: prior to JDK-21, the
javac
compiler was omitting some potentially ambiguous overload warnings enabled by the-Xlint:overloads
option.JDK-8305092: Improve Thread.sleep(millis, nanos) for sub-millisecond granularity: as it says, the Thread.sleep(long millis, int nanos) is now able to perform sub-millisecond sleep.
JDK-8302659: Modernize Windows native code for NetworkInterface: the change may impact the implementations that lookup of network interfaces by calling NetworkInterace.getByName(String name) method however the display name returned by NetworkInterface.getDisplayName() has not been changed.
JDK-8300869: Make use of the Double.toString(double) algorithm in java.util.Formatter: replaces java.util.Formatter algorithm to format
double
andfloat
with a the one used by Double.toString(double d).JDK-8205129: Remove java.lang.Compiler: the
java.lang.Compiler
class was deprecated for removal long time ago and it has been removed in JDK-21.JDK-8297295: Remove ThreadGroup.allowThreadSuspension: the method
ThreadGroup.allowThreadSuspension
was deprecated for removal since JDK-14 and its time has come.
The JDK-21 changeset looks already impressive but ... we are not done yet, let us walk through the standard library changes.
New interfaces java.lang.constant.ModuleDesc and java.lang.constant.PackageDesc for describing
Module
andPackage
constants respectively.The com.sun.management.ThreadMXBean interface got one new default method:
The class java.util.concurrent.DelayQueue overrides:
As part of JDK-8301226, the java.lang.Math got new static method family:
Under the same JDK-8301226 issue, the java.lang.StrictMath has those new methods too:
In scope of JDK-8302323, the rare addition of the new methods to java.lang.StringBuilder class has happened:
And similarly, still under JDK-8302323, to java.lang.StringBuffer class:
The java.util.Locale was also refreshed with:
The JDK-8302590 and JDK-8305486 bring improvements to java.lang.String class:
The JDK-8305486 also touched the java.util.regex.Pattern class:
Probably the most love in JDK-21 was directed to emojis, with JDK-8303018 adding new emoji properties to java.lang.Character:
The java.util.regex.Pattern got some of the emoji share as well in scope of JDK-8305107: one can match characters that have emoji-related properties with the new
\p{IsXXX}
constructs, for example:Pattern.compile("\\p{IsEmoji}").matcher("π").matches()
From the security perspective, JDK-21 is pretty packed with enhancements. Some of them we have highlighted above but a few more deserve special mentions (if you need a comprehensive look, please check out JDK 21 Security Enhancements article):
JDK-8298127: HSS/LMS Signature Verification: implements support for Leighton-Micali Signatures (LMS) as described in RFC-8554. LMS is an approved software signing algorithm for CNSA 2.0, with SHA-256/192 parameters recommended.
JDK-8288050: Add support of SHA-512/224 and SHA-512/256 to the PBKDF2 and PBES2 impls in SunJCE provider: the SunJCE provider is enhanced with additional PBES2 Cipher and Mac algorithms, such as those using SHA-512/224 and SHA-512/256 message digests.
JDK-8301553: Support Password-Based Cryptography in SunPKCS11: supports an initial set of Password-Based Cryptography algorithms in the SunPKCS11 security provider.
JDK-8305091: Change ChaCha20 cipher init behavior to match AES-GCM: allows ChaCha20 decrypt-mode Cipher objects to reuse the key and nonce, conforming to the same rules that AES-GCM does.
JDK-8179502: Enhance OCSP, CRL and Certificate Fetch Timeouts: delivers an enhanced syntax for properties related to certificate, CRL, and OCSP connect and read timeouts. The new system properties
com.sun.security.ocsp.readtimeout
,com.sun.security.cert.timeout
andcom.sun.security.cert.readtimeout
have been introduced to control this behavior.
From all perspectives, JDK-21 looks like the release worth migrating to (it is supposed to be LTS), despite the fact there are unforeseen delays announced by some vendors.
I πΊπ¦ stand πΊπ¦ with πΊπ¦ Ukraine.
No comments:
Post a Comment