
On September 19, 2023, major launch events celebrated the release of Java 21, the then-latest long-term support (LTS) version (after Java 17 and before Java 25).
The highlights of Java 21:
- One of the most significant innovations in the history of Java, virtual threads, has been finalized.
- Also finalized were two new Java language features from Project Amber: Record Patterns and Pattern Matching for switch.
- A new, convenient interface,
SequencedCollection, provides direct access to an ordered collection’s first and last elements. - Two long-awaited features that other languages have long offered are finally available in Java (for now as a preview feature): String Templates and Unnamed Patterns and Variables.
Virtual Threads – JEP 444
When scaling server applications, threads are often a bottleneck. Their number is limited, and they often have to wait for events, such as the response of a database query or a remote call, or they are blocked by locks.
Previous approaches, such as CompletableFuture or reactive frameworks, result in code that is extremely difficult to read and maintain.
For several years, clever developers have been working on a better solution within the scope of Project Loom. In Java 19, the time had finally come: Virtual threads were introduced as a preview feature.
In Java 21, virtual threads are finalized via JDK Enhancement Proposal 444 and are thus ready for production use.
What Are Virtual Threads?
Unlike reactive code, virtual threads allow programming in the familiar, sequential thread-per-request style.
Sequential code is not only easier to write and read but also easier to debug since we can use a debugger to trace the program flow step by step, and stack traces reflect the expected call stack. Anyone who has ever tried to debug a reactive application will know what I mean.
Writing scalable applications with sequential code is made possible by allowing many virtual threads to share a platform thread (the name given to the conventional threads provided by the operating system). When a virtual thread has to wait or is blocked, the platform thread will execute another virtual thread.
That allows us to run several million (!) virtual threads with just a few operating system threads.
The best part is that we don’t have to change existing Java code. We simply tell our application framework to use virtual threads instead of platform threads.
If you want to know precisely how virtual threads work, their limitations, and what happens behind the scenes, you can read all about them in the main article on virtual threads.
Changes From the Preview Version
In the preview versions, it was possible to configure a virtual thread so that it cannot have ThreadLocal variables – since these can be very expensive, virtual threads should instead use Scoped Values, also delivered in Java 21 as a preview feature. This possibility was removed again so that as much existing code as possible can run in virtual threads without changes.
In addition, virtual threads created directly via Thread.Builder are now monitored throughout their lifetime by default and appear in the new thread dump (jcmd <pid> Thread.dump_to_file -format=json <file>). In the preview versions, this applied only to virtual threads created via Executors.newVirtualThreadPerTaskExecutor().
Sequenced Collections – JEP 431
What is the easiest way to access the last element of a list? Unless you use additional libraries or helper methods, in Java – so far – it is the following:
var last = list.get(list.size() - 1);
In Java 21, we can finally replace this behemoth with a short and concise call:
var last = list.getLast();
Perhaps you’ve also needed to access the first element of a LinkedHashSet? Until now, this required the following detour:
var first = linkedHashSet.iterator().next();
In Java 21, that’s easier, too:
var first = linkedHashSet.getFirst();
To access the last element of a LinkedHashSet, you even had to iterate over the complete set! This can now also be done easily with getLast().
The new methods come from three interfaces that were introduced by JEP 431. The following sections give you an overview. You can find all methods with examples and pitfalls in the article Sequenced Collections in Java.
SequencedCollection Interface
SequencedCollection stands for a collection whose elements have a defined order, the so-called encounter order. List and Deque extend the interface directly. LinkedHashSet and SortedSet – and thus TreeSet – are sequenced collections via SequencedSet.
In addition to getFirst() and getLast(), SequencedCollection defines the methods addFirst(), addLast(), removeFirst(), and removeLast(). The seventh method, reversed(), returns the elements in reverse order – not as a copy but as a view of the original collection.
SequencedSet Interface
SequencedSet extends Set and SequencedCollection and defines no further methods. If an element is already in the set, addFirst() and addLast() on a LinkedHashSet move it to the front or to the back, respectively.
The following diagram shows the two interfaces in the hierarchy of the collections. The interfaces introduced with Java 21 have a dark blue border, the older interfaces and classes with an encounter order a light blue one, and the interfaces without an encounter order a gray one:
SequencedMap Interface
In the Collections Framework, maps have a hierarchy of their own. For maps with an encounter order, there is therefore the SequencedMap interface. LinkedHashMap implements it directly, TreeMap via SortedMap:
SequencedMap defines firstEntry(), lastEntry(), pollFirstEntry(), pollLastEntry(), putFirst(), putLast(), and reversed(). In addition, sequencedKeySet(), sequencedValues(), and sequencedEntrySet() return the keys, the values, and the entries as a sequenced collection.
New Collections Methods
For the new interfaces, the Collections class got the methods unmodifiableSequencedCollection(), unmodifiableSequencedSet(), and unmodifiableSequencedMap(), which return unmodifiable views, as well as newSequencedSetFromMap().
Record Patterns – JEP 440
“Record Patterns” were first introduced in Java 19 as a preview feature. They can be combined with Pattern Matching for instanceof and Pattern Matching for switch to access the fields of a record without explicit casts and without using access methods.
This sounds more complicated than it is. The best way to explain record patterns is with an example:
We’ll start with a simple record (if you’re unfamiliar with records, you can find an introduction to Java records here).
public record Position(int x, int y) {}
Now let’s assume we have an arbitrary object and want to perform a particular action with it depending on its class – for instance, print something on the console.
We could do that using Pattern Matching for instanceof, introduced in Java 16, as follows:
public void print(Object o) {
if (o instanceof Position p) {
System.out.printf("o is a position: %d/%d%n", p.x(), p.y());
} else if (o instanceof String s) {
System.out.printf("o is a string: %s%n", s);
} else {
System.out.printf("o is something else: %s%n", o);
}
}
Instead of the pattern Position p, we can now also match a so-called record pattern – namely Position(int x, int y) – and then access the variables x and y directly in the following code instead of using p.x() and p.y():
public void print(Object o) {
if (o instanceof Position(int x, int y)) {
System.out.printf("o is a position: %d/%d%n", x, y);
} else if (o instanceof String s) {
System.out.printf("o is a string: %s%n", s);
} else {
System.out.printf("o is something else: %s%n", o);
}
}
Record patterns work with Pattern Matching for switch as well, and they can be nested: a record pattern can contain record patterns in turn. What that looks like is shown in the section Nested Record Patterns of the article on pattern matching, and why record patterns show their strength above all in sealed hierarchies, in the section Putting It All Together.
Record Patterns have been finalized with JDK Enhancement Proposal 440 – with one change from the last preview version:
Record Patterns in for Loops Were Removed
Java 20 introduced the ability to use record patterns in for loops as well, as in the following example:
List<Position> positions = ...
for (Position(int x, int y) : positions) {
System.out.printf("(%d, %d)%n", x, y);
}
This option was removed in the final version of the feature, with the prospect of reintroducing it in a future Java release.
Pattern Matching for switch – JEP 441
“Pattern Matching for switch” was first introduced in Java 17 as a preview feature and, in combination with Record Patterns, allows switch statements and expressions to be formulated over any object. Here is an example:
Object obj = getObject();
switch (obj) {
case String s when s.length() > 5 -> System.out.println(s.toUpperCase());
case String s -> System.out.println(s.toLowerCase());
case Integer i -> System.out.println(i * i);
case Position(int x, int y) -> System.out.println(x + "/" + y);
default -> {}
}
The compiler checks whether the switch covers all possible cases (exhaustiveness analysis). With a sealed class hierarchy whose types all appear as a case, it therefore needs no default branch. When exactly a switch is exhaustive, and in which order the cases must appear, is shown in the article on pattern matching.
With JDK Enhancement Proposal 441, Pattern Matching for switch was finalized with two changes compared to the last preview version:
“Parenthesized Patterns” Were Removed
Until Java 20, it was possible to put patterns in parentheses like this:
Object obj = getObject();
switch (obj) {
case (String s) when s.length() > 5 -> System.out.println(s.toUpperCase());
case (String s) -> System.out.println(s.toLowerCase());
case (Integer i) -> System.out.println(i * i);
case (Position(int x, int y)) -> System.out.println(x + "/" + y);
default -> {}
}
Since the parentheses served no purpose, this option was removed in the final version of the feature.
Qualified Enum Constants
Until now, we could only implement a switch expression over enum constants using a “guarded pattern” – i.e., a pattern combined with when.
I’ll show you what this means with an example. Here are two enums that implement a sealed interface:
public sealed interface Direction permits CompassDirection, VerticalDirection {}
public enum CompassDirection implements Direction { NORTH, SOUTH, EAST, WEST }
public enum VerticalDirection implements Direction { UP, DOWN }
Until Java 20, we had to implement a switch over all possible directions as follows:
void flyJava20(Direction direction) {
switch (direction) {
case CompassDirection d when d == CompassDirection.NORTH ->
System.out.println("Flying north");
case CompassDirection d when d == CompassDirection.SOUTH ->
System.out.println("Flying south");
case CompassDirection d when d == CompassDirection.EAST ->
System.out.println("Flying east");
case CompassDirection d when d == CompassDirection.WEST ->
System.out.println("Flying west");
case VerticalDirection d when d == VerticalDirection.UP ->
System.out.println("Gaining altitude");
case VerticalDirection d when d == VerticalDirection.DOWN ->
System.out.println("Losing altitude");
default -> throw new IllegalArgumentException("Unknown direction: " + direction);
}
}
With this notation, the exhaustiveness analysis does not apply, i.e., even though we have implemented all possible cases, a default branch is necessary. Otherwise, a compiler error occurs.
In Java 21, we can now formulate the same logic much more concisely by directly specifying the qualified enum constants (“qualified” means: including the class name):
void flyJava21(Direction direction) {
switch (direction) {
case CompassDirection.NORTH -> System.out.println("Flying north");
case CompassDirection.SOUTH -> System.out.println("Flying south");
case CompassDirection.EAST -> System.out.println("Flying east");
case CompassDirection.WEST -> System.out.println("Flying west");
case VerticalDirection.UP -> System.out.println("Gaining altitude");
case VerticalDirection.DOWN -> System.out.println("Losing altitude");
}
}
The compiler also recognizes that all cases are covered and no longer requires a default branch.
New Methods in String, StringBuilder, StringBuffer, Character, and Math
Not all changes have a JEP. Some new methods in String, StringBuilder, StringBuffer, Character, and Math can only be found in the API documentation and the bug tracker. Conveniently there is the Java Version Almanac, with which one can compare different API versions comfortably.
New String Methods
The String class has been extended by the following methods:
String.indexOf(String str, int beginIndex, int endIndex)– searches the specified substring in a subrange of the string.String.indexOf(char ch, int beginIndex, int endIndex)– searches the specified character in a subrange of the string.String.splitWithDelimiters(String regex, int limit)– splits the string at substrings matched by the regular expression and returns an array of all parts and splitting strings. The string is split at mostlimit-1times, i.e., the last element of the array could be further divisible.
Here is an example of splitWithDelimiters():
String string = "the red brown fox jumps over the lazy dog";
String[] parts = string.splitWithDelimiters(" ", 5);
System.out.println(
Arrays.stream(parts).collect(Collectors.joining("', '", "'", "'")));
These lines of code print the following:
'the', ' ', 'red', ' ', 'brown', ' ', 'fox', ' ', 'jumps over the lazy dog'
There is no JEP for these changes; they are tracked in the bug tracker under JDK-8303648 (indexOf(String, int, int)), JDK-8302590 (indexOf(char, int, int)), and JDK-8305486 (splitWithDelimiters()).
New StringBuilder and StringBuffer Methods
Both StringBuilder and StringBuffer have been extended by the following two methods:
repeat(CharSequence cs, int count)– appends to theStringBuilderorStringBufferthe stringcs–counttimes.repeat(int codePoint, int count)– appends the specified Unicode code point to theStringBuilderorStringBuffer–counttimes. A variable or constant of typecharcan also be passed as code point.
Here is an example that calls repeat() once with a string, once with a code point and once with a character:
StringBuilder sb = new StringBuilder();
sb.repeat("Hello ", 2);
sb.repeat(0x1f600, 5);
sb.repeat('!', 3);
System.out.println(sb);
This code prints the following:

There is no JEP for this change; it is tracked in the bug tracker under JDK-8302323.
New Character Methods
Speaking of emojis … the following new methods are provided by the Character class:
isEmoji(int codePoint)isEmojiComponent(int codePoint)isEmojiModifier(int codePoint)isEmojiModifierBase(int codePoint)isEmojiPresentation(int codePoint)isExtendedPictographic(int codePoint)
These methods check whether the passed Unicode code point stands for an emoji or a variant of it. You can read exactly what these variants mean in Appendix A of the Unicode Emoji Specification.
There is no JEP for this change; it is tracked in the bug tracker under JDK-8303018.
New Math Methods
How many times have we written the following piece of code to ensure that a number is in a given numeric range, or clamped into that range otherwise?
if (value < min) {
value = min;
} else if (value > max) {
value = max;
}
From now on, we can use Math.clamp() for exactly this purpose. The method comes in the following four variants:
int clamp(long value, int min, int max)long clamp(long value, long min, long max)double clamp(double value, double min, double max)float clamp(float value, float min, float max)
These methods check whether value is in the range min to max. If value is less than min, they return min; if value is greater than max, they return max.
There is no JEP for this change; it is tracked in the bug tracker under JDK-8301226.
Preview and Incubator Features
Even though Java 21 is a Long-Term Support release, it contains new and resubmitted preview features. Preview features must be explicitly enabled with the VM option --enable-preview and are usually slightly revised in subsequent Java versions.
String Templates (Preview) – JEP 430
String templates offer a dynamic way of generating strings by replacing placeholders with variable values and computed results at runtime. This process, known as string interpolation, makes it possible to compose complex strings efficiently:
int a = ...;
int b = ...;
String result = STR."\{a} times \{b} = \{Math.multiplyExact(a, b)}";
The following replacements are made during execution:
\{a}is dynamically replaced by the current value ofa.\{b}is replaced by the value ofb.\{Math.multiplyExact(a, b)}is replaced by the result of the method callMath.multiplyExact(a, b).
String templates were introduced in Java 21 as a preview feature through JDK Enhancement Proposal 430. You can find a more detailed description in the main article on string templates.
Unnamed Patterns and Variables (Preview) – JEP 443
Often we encounter the need to declare variables that ultimately go unused. Typical examples include Exceptions, lambda parameters, and pattern variables.
Consider an example where the Exception variable e remains unused:
try {
int number = Integer.parseInt(string);
} catch (NumberFormatException e) {
System.err.println("Not a number");
}
In this instance, the lambda parameter k is unused:
map.computeIfAbsent(key, k -> new ArrayList<>()).add(value);
And in this record pattern on a Path with a start and an end position – record Path(Position from, Position to) {} – the pattern variable position2 is unused:
if (object instanceof Path(Position(int x1, int y1), Position position2)) {
System.out.printf("object is a path starting at x = %d, y = %d%n", x1, y1);
}
In Java 21, unnamed variables and patterns – initially as a preview feature – offer a more elegant solution by letting you replace the names of unused variables, or even an entire pattern, with an underscore (_):
Instead of the Exception variable e, we can use _:
try {
int number = Integer.parseInt(string);
} catch (NumberFormatException _) {
System.err.println("Not a number");
}
Instead of the Lambda parameter k, we use _:
map.computeIfAbsent(key, _ -> new ArrayList<>()).add(value);
And the partial pattern Position position2 can also be replaced with _:
if (object instanceof Path(Position(int x1, int y1), _)) {
System.out.printf("object is a path starting at x = %d, y = %d%n", x1, y1);
}
Unnamed patterns and variables are defined in JDK Enhancement Proposal 443. In the JEP, you can find some more examples of using unnamed variables. You can find further details and a deeper examination of these features in the main article about unnamed variables and patterns.
Unnamed Classes and Instance Main Methods (Preview) – JEP 445
When novice programmers write their first Java program, it usually looks like this:
public class HelloWorld {
public static void main(String[] args) {
System.out.println("Hello world!");
}
}
And that is only if the class is in the “unnamed package.” Otherwise, a package declaration is also required.
Experienced Java developers will recognize the elements of this program at first glance. But beginners are overwhelmed by visibility modifiers, complex concepts like classes and static methods, unused method arguments, and a System.out.
Wouldn’t it be nice if most of this could be eliminated? Like this:

Exactly that is possible in Java 21, thanks to JDK Enhancement Proposal 445! The following code is a valid, complete Java program as of now:
void main() {
System.out.println("Hello world!");
}
Since the feature is still in the preview stage, you need to compile and run the code as follows:
$ javac --enable-preview --source 21 HelloWorld.java
$ java --enable-preview HelloWorld
Hello world!
Alternatively, you can run the program without explicitly compiling it:
$ java --enable-preview --source 21 HelloWorld.java
Hello world!
You can find the latest version of this feature in the Compact Source Files and Instance Main Methods section (under this name, the feature was finalized in Java 25 with JEP 512) of the article on the Java main method.
The “Unnamed Class”
By the way, the main() method still is in a class: the so-called “unnamed class.” This is not an entirely new concept. There was already the “unnamed package” (a class without a package declaration) and the “unnamed module” (a Java source code directory without a module-info.java file).
Just as named modules cannot access code in the unnamed module, and just as code from named packages cannot access unnamed packages, code from named classes cannot access unnamed classes.
The unnamed class may also have fields and other methods. The following is also a valid and complete Java program:
final String HELLO_TEMPLATE = "Hello %s!";
void main() {
System.out.println(hello("world"));
}
String hello(String name) {
return HELLO_TEMPLATE.formatted(name);
}
Launch Protocol
The main() method may, of course, still be marked as public static and contain the String[] argument. It may also be only public or only static. Or protected. Theoretically, a class can also contain two main() methods – for example, the following would also be allowed:
protected static void main() {
// ...
}
public void main(String[] args) {
// ...
}
In such a case, the so-called “launch protocol” decides which of the main() methods to start. The launch protocol searches in the following order; the visibility modifier is irrelevant (only private is not allowed):
static void main(String[] args)static void main()void main(String[] args)– this method may also be inherited from a superclass (but this only works in a named class)void main()– also, this method may be inherited from a superclass
So in the example above, the JVM would start the static method with no parameters (launch priority 2).
Scoped Values (Preview) – JEP 446
Scoped Values are a modern alternative to ThreadLocal variables that can be used well in the context of virtual threads.
Scoped values have the following advantages over ThreadLocal variables:
- They are only valid for a defined period (“scope”).
- They are immutable.
- And therefore, they can be inherited without having to be copied (as is the case with
InheritableThreadLocal).
The first two points also lead to cleaner and, thus, less error-prone program code.
Scoped values were introduced in Java 20 as an incubator project. In Java 21, JDK Enhancement Proposal 446 upgrades them to a preview project. The ScopedValue class has moved from the incubator module jdk.incubator.concurrent to the java.lang package and is now enabled with --enable-preview instead of --add-modules. In addition, the static shorthand methods ScopedValue.where(key, value, op) have been renamed to runWhere() for a Runnable and callWhere() for a Callable, and a new getWhere() takes a Supplier.
You can learn how scoped values work in the main article about scoped values.
Structured Concurrency (Preview) – JEP 453
To divide a task into several subtasks to be processed in parallel, Java has so far provided two high-level constructs:
- Parallel streams to perform the same operation in parallel on multiple elements
ExecutorServiceto perform different tasks in parallel
ExecutorService is very powerful, quickly driving up the implementation effort for simple parallel tasks. For example, it is pretty complicated (and thus error-prone) to detect when a subtask has thrown an exception and immediately and cleanly abort all other subtasks still running.
Structured concurrency provides a new, easy-to-implement mechanism for splitting a task into subtasks to be processed in parallel, merging the results of the subtasks, and terminating subtasks if their results are no longer needed.
You can learn how this works in the main article about Structured Concurrency.
Structured concurrency was first introduced in Java 19 in the incubator stage and extended in Java 20 to allow subtasks to inherit the parent thread’s scoped values described in the previous section.
In Java 21, JDK Enhancement Proposal 453 changed the return type of StructuredTaskScope.fork() – the method that starts subtasks – from Future to Subtask. This should emphasize the difference between structured concurrency and the ExecutorService API.
For example, Future.get() waits for a result, while Subtask.get() must only be called once a subtask is finished – otherwise the method throws an IllegalStateException. And Subtask.state() returns a state specific to structured concurrency, while Future.isDone() and isCancelled() do not.
In addition, StructuredTaskScope has moved from the incubator module jdk.incubator.concurrent to the java.util.concurrent package.
Foreign Function & Memory API (Third Preview) – JEP 442
Until now, anyone who wanted to access code outside the JVM (e.g., functions in C libraries) or memory not managed by the JVM had to use the Java Native Interface (JNI). Anyone who has ever done this knows how cumbersome, error-prone, and slow JNI is.
A replacement for JNI has been in the works since Java 14, initially in incubator projects. In Java 19, a united “Foreign Function & Memory API” was introduced as a first preview version.
I will demonstrate what this API facilitates with a simple example.
The following code shows how to obtain a handle to the strlen() method of the standard C library, place the string “Happy Coding!” in native memory (i.e., outside the Java heap), and then execute the strlen() method on that string:
public class FFMTest21 {
public static void main(String[] args) throws Throwable {
// 1. Get a lookup object for commonly used libraries
SymbolLookup stdlib = Linker.nativeLinker().defaultLookup();
// 2. Get a handle to the "strlen" function in the C standard library
MethodHandle strlen = Linker.nativeLinker().downcallHandle(
stdlib.find("strlen").orElseThrow(),
FunctionDescriptor.of(JAVA_LONG, ADDRESS));
// 3. Convert Java String to C string and store it in off-heap memory
try (Arena offHeap = Arena.ofConfined()) {
MemorySegment str = offHeap.allocateUtf8String("Happy Coding!");
// 4. Invoke the foreign function
long len = (long) strlen.invoke(str);
System.out.println("len = " + len);
}
// 5. Off-heap memory is deallocated at end of try-with-resources
}
}
In the code, only one name has changed compared to the Java 20 variant: Arena.ofConfined() was previously called openConfined(). Behind it lies a change made by JEP 442: The SegmentScope class has been removed; the lifetime of native memory segments is now determined by the Arena alone. In addition to Arena.ofConfined() and Arena.ofShared(), there is Arena.ofAuto(), whose memory is freed by the garbage collector, and Arena.global(), whose memory is never freed.
Furthermore, the VaList class has been removed, and Java 21 adds AddressLayout.withTargetLayout(), which specifies the layout an address points to, and the linker option Linker.Option.isTrivial() for very short native functions that do not call back into Java.
You can compile and execute the small example program as follows:
$ javac --enable-preview --source 21 FFMTest21.java
Note: FFMTest21.java uses preview features of Java SE 21.
Note: Recompile with -Xlint:preview for details.
$ java --enable-preview --enable-native-access=ALL-UNNAMED FFMTest21
len = 13
Of course, you can also combine both steps into one:
$ java --enable-preview --source 21 --enable-native-access=ALL-UNNAMED FFMTest21.java
Note: FFMTest21.java uses preview features of Java SE 21.
Note: Recompile with -Xlint:preview for details.
len = 13
Accessing native memory and calling native code is a rather specialized area. Very few programmers will come into direct contact with it. Therefore, I will not go into further detail at this point. You can find details about the current state of the FFM API in JDK Enhancement Proposal 442.
Vector API (Sixth Incubator) – JEP 448
In Java 21, the new Vector API is submitted as an incubator feature for the sixth consecutive release through JDK Enhancement Proposal 448. New in this round is the xor() method for masks (VectorMask).
The Vector API makes it possible to perform mathematical vector operations efficiently. A vector operation is, for example, a vector addition, as you may remember from math classes:

Modern CPUs can perform such operations up to a particular vector size with a single instruction. The Vector API enables the JVM to map such operations to the most efficient instructions of the underlying CPU architecture.
Other Changes in Java 21
Let’s move on to the changes we won’t usually be confronted with on a daily basis. At least not directly. Unless, for example, we are responsible for selecting the garbage collector and its optimization. Then the following JEP should be interesting:
Generational ZGC – JEP 439
The Z Garbage Collector – ZGC for short – was introduced in Java 11 as an experimental feature and became production-ready in Java 15. ZGC promises sub-millisecond pause times – the standard garbage collector, G1, by contrast, ranges from milliseconds to seconds.
Until now, ZGC made no distinction between “old” and “new” objects. However, according to the “Weak Generational Hypothesis,” precisely this difference can have a significant impact on the performance of an application.
According to this hypothesis, most objects die shortly after their creation, whereas objects that have survived a few GC cycles tend to stay alive even longer.
A so-called “generational garbage collector” takes advantage of this by dividing the heap into two logical areas: a “young generation,” in which new objects are created, and an “old generation,” into which objects that have reached a certain age are moved. Since objects in the old generation are likely to become even older, an application’s performance can be improved by having the garbage collector scan the old generation less frequently.
However, implementing a garbage collector with multiple generations is significantly more complex than implementing a non-generational garbage collector because of the potential inter-generation references.
Therefore, we had to wait until Java 21 for JDK Enhancement Proposal 439 to make the Z Garbage Collector a generational one.
For a transition period, both variants of the ZGC will be available. The VM option -XX:+UseZGC still activates the old non-generational variant. To activate the new generational variant, you must specify the following VM options:
-XX:+UseZGC -XX:+ZGenerational
You can read about how exactly Generational ZGC works in JEP 439.
Deprecate the Windows 32-bit x86 Port for Removal – JEP 449
The 32-bit version of Windows 10 is hardly used anymore, support ended in October 2025, and Windows 11 – on the market since October 2021 – has never been offered in a 32-bit version.
Accordingly, there is hardly any need for a 32-bit Windows version of the JDK.
To speed up the development of the JDK, virtual threads have not been implemented for 32-bit Windows. Anyone who tries to start a virtual thread on 32-bit Windows will get a platform thread instead.
JDK Enhancement Proposal 449 marks the 32-bit Windows port as “deprecated for removal.”
Prepare to Disallow the Dynamic Loading of Agents – JEP 451
If you have ever used a Java profiler, you probably started the application to be analyzed with a parameter like -agentpath:<path-to-agent-library>. This loads a so-called “agent” into the application, which modifies it at runtime to perform the necessary measurements and either write the results to a file or send them to the profiler’s front end.
If the application was started without this parameter, the agent can also be “injected” into the JVM afterward using the so-called “Attach API.”
This so-called “dynamic loading” is activated by default and thus represents a considerable security risk.
In a future Java version, dynamic loading will be disabled by default and can only be explicitly enabled via the VM option -XX:+EnableDynamicAgentLoading.
Since such a change cannot be made overnight, dynamic loading is still allowed in Java 21 but can be disabled with -XX:-EnableDynamicAgentLoading. In addition, warnings are now displayed when an agent is loaded via the Attach API.
This change is defined in JDK Enhancement Proposal 451. There you will also find a comprehensive list of security risks.
Key Encapsulation Mechanism API – JEP 452
Key Encapsulation Mechanism (KEM) is a modern encryption technology that enables the exchange of symmetric keys via an asymmetric encryption process.
Through JDK Enhancement Proposal 452, the JDK provides an API for KEM.
The new class javax.crypto.KEM has two sides: Using the receiver’s public key, the sender creates a secret key via a KEM.Encapsulator, together with the encapsulation – a message from which the receiver recovers the same secret key via a KEM.Decapsulator using its private key. Java 21 ships DHKEM as the mechanism, which is based on the Diffie-Hellman key exchange:
// Receiver side
var kpg = KeyPairGenerator.getInstance("X25519");
var kp = kpg.generateKeyPair();
// Sender side
var sender = KEM.getInstance("DHKEM").newEncapsulator(kp.getPublic());
var encapsulated = sender.encapsulate();
SecretKey k1 = encapsulated.key();
// Receiver side
var receiver = KEM.getInstance("DHKEM").newDecapsulator(kp.getPrivate());
SecretKey k2 = receiver.decapsulate(encapsulated.encapsulation());
k1 and k2 then contain the same key. DHKEM offers no protection against future quantum computers, as they threaten Diffie-Hellman methods.
Thread.sleep(millis, nanos) Is Now Able to Perform Sub-Millisecond Sleeps
When calling Thread.sleep(millis, nanos), the nanos value was virtually ignored until now. It was only when nanos was greater than 500,000 (i.e., half a millisecond) that the millis value was incremented by one, and then Thread.sleep(millis) was called.
As of Java 21, at least on Linux and macOS, the wait time is passed to the operating system (or to the “unparker” in the case of a virtual thread) at nanosecond granularity. The actual waiting time still depends on the precision of the system clock and the scheduler.
There is no JEP for this change; it is tracked in the bug tracker under JDK-8305092.
Last Resort G1 Full GC Moves Humongous Objects
When using the G1 garbage collector (G1GC), the available heap memory is divided into up to 2,048 regions. Objects larger than half of such a region are called “humongous objects.”
Humongous objects have never been moved in memory. Thus, an OutOfMemoryError could occur if the heap was heavily fragmented, even if there was still enough memory available overall – just not in a contiguous region.
Starting with Java 21, even humongous objects are relocated – however, only if, after a full GC, there’s still insufficient contiguous memory available. This process can take quite long (up to several seconds) depending on the size of the heap.
There is no JEP for this change; it is tracked in the bug tracker under JDK-8191565.
Implement Alternative Fast-Locking Scheme
When a thread enters a synchronized block on an object, the JVM must store this information somewhere to prevent another thread from entering the critical section.
Until now, this has been done using a mechanism called “stack locking”. Here, the object header’s Mark Word is replaced by a pointer to a data structure on the stack, which in turn contains the Mark Word and further information about the lock state.
Firstly, this mechanism makes it more difficult to access the actual data of the Mark Word. Secondly, the pointer to the stack is one reason for the so-called pinning of virtual threads.
In Java 21, an alternative locking mechanism is offered, called “lightweight locking”. Here, only the two “tag bits” in the Mark Word are changed; additional lock data structures are referenced from a hash table and a thread-local cache. The Mark Word can thus always be accessed directly.
Lightweight locking can be activated using the VM option described in the next section.
There is no JEP for this change; it is tracked in the bug tracker under JDK-8291555.
Add Experimental -XX:LockingMode Flag
Locking usually occurs in two steps:
- When a thread enters a critical section, only the information that the section is locked is stored in the monitor object (the object that is specified in parentheses behind
synchronized) – further information is not necessary at this time. - Only when another thread tries to enter the critical section, a list of waiting threads must be created, among other things. For this purpose, an additional data structure is created, the so-called “heavyweight monitor”.
Step 1 was previously performed by the so-called “stack locking”. Using the VM option -XX:+UseHeavyMonitors, step 1 could be skipped and the “heavyweight monitor” created directly.
To activate the new locking mechanism described in the previous section, Java 21 introduces the new VM option -XX:LockingMode, with the following options:
| VM Option | Name | Description |
|---|---|---|
-XX:LockingMode=0 | LM_MONITOR | Only heavyweight monitor objects (step 1 is skipped); corresponds to the previous option -XX:+UseHeavyMonitors |
-XX:LockingMode=1 | LM_LEGACY | Stack locking + monitor objects in case of contention; corresponds to the previous default behavior |
-XX:LockingMode=2 | LM_LIGHTWEIGHT | Lightweight locking + monitor objects in case of contention; this is the new mode described in the previous section. |
Since the feature is currently still in the experimental stage, you must also specify the VM option -XX:+UnlockExperimentalVMOptions.
There is no JEP for this change; it is tracked in the bug tracker under JDK-8305999.
JFR: Summary views
Since Java 21, the jfr view command analyzes a Java Flight Recorder recording directly on the command line. It comes with predefined analyses, so-called views, that summarize the events in a table, for example:
hot-methods: which methods are executed most often,allocation-by-site: which code creates the most objects,contention-by-site: where threads wait to enter asynchronizedblock,gc: the individual garbage collections.
$ jfr view hot-methods recording.jfr
Instead of a view, you can also specify an event type, e.g., jdk.GarbageCollection; jfr view all-views recording.jfr prints all views at once. And with jcmd <pid> JFR.view hot-methods, you display a view from a running recording without writing a file first.
How to find CPU load, allocations, waiting times, a memory leak, and exceptions with these views is shown in the section Five Questions for the Recording of the article on the Java Flight Recorder.
There is no JEP for this change; it is tracked in the bug tracker under JDK-8306703.
Complete List of All Changes in Java 21
In this article, you have learned about all JDK Enhancement Proposals delivered in Java 21. You can find additional minor changes in the official Java 21 Release Notes.
Summary
The LTS release Java 21 brings one of the most significant changes in Java history with the finalization of virtual threads, which will significantly simplify the implementation of highly scalable server applications.
Record Patterns, Pattern Matching for switch, Sequenced Collections, String Templates, and Unnamed Patterns and Variables (the last two are still in the preview stage) make the language more expressive and robust.
Unnamed Classes and Instance Main Methods (also in the preview stage) make it easier for programmers to get started with the language without having to understand complex constructs like classes and static methods right at the beginning.
Various other changes complement the release as usual.
On support: the free updates for Oracle JDK 21 under the No-Fee Terms and Conditions license (NFTC) ended in September 2026; since then, they have been released under the paid OTN license. With a Java SE subscription, you get Premier Support until September 2028 and Extended Support until September 2031. Free updates remain available from other distributions – Eclipse Temurin, for example, until at least December 2029.
The Java 21 builds are still available in the OpenJDK archive and from Oracle. For new projects, you are better off with the current LTS version, Java 25.
If this article has helped you, I would greatly appreciate a positive review on my ProvenExpert profile. Your feedback helps me improve my content and motivates me to write new informative articles.




