Java 21 features: what's new in Java 21 LTS, with examples

Java 21 is the long-term-support release that made virtual threads, record patterns, pattern matching for switch and sequenced collections standard. Here is every important feature, what each one does in a line of code, which were only previews, and what to watch when you upgrade from Java 17.

A red JDK 21 badge reading LTS, September 2023, next to the heading 15 JEPs, these matter most. Six tiles list final features: virtual threads, record patterns, pattern matching for switch (highlighted yellow), sequenced collections, generational ZGC and the key encapsulation API. A row of dashed pills lists preview or incubator features: string templates, unnamed underscore, instance main, scoped values and structured concurrency.
Fig. 1 — Java 21 shipped 15 JEPs. Six of them changed everyday Java code; several more were previews of what came next.

Java ships a new version every six months, but most teams only move between long-term-support (LTS) releases: 8, 11, 17, and then Java 21, released on 19 September 2023. It’s the release that changed how everyday Java looks: cheap threads for blocking code, data classes you can take apart in a switch, and collections that finally know which element is first and last.

This guide lists the Java 21 features that matter, with a short example of each and a link to a full explanation. It also separates what was final (ready for production) from what was only a preview, because that difference trips people up.

Java 21 at a glance

Java 21 delivered 15 JEPs (JDK Enhancement Proposals). Here they are, grouped by what you can actually use:

Feature JEP Status
Virtual threads 444 Final
Record patterns 440 Final
Pattern matching for switch 441 Final
Sequenced collections 431 Final
Generational ZGC 439 Final (opt-in)
Key Encapsulation Mechanism API 452 Final
String templates 430 Preview, later withdrawn
Unnamed patterns and variables (_) 443 Preview, final in 22
Unnamed classes and instance main 445 Preview, final in 25
Scoped values 446 Preview, final in 25
Structured concurrency 453 Preview, still preview in 26
Foreign Function & Memory API 442 Preview, final in 22
Vector API 448 Incubator
Deprecate Windows 32-bit x86 port 449 Deprecation
Warn on dynamic agent loading 451 Warning

The four features that change everyday code

1. Virtual threads

The headline feature. Before Java 21, every Java thread was bound to an operating-system thread, so a server could only wait on a few thousand things at once. A virtual thread releases its OS thread whenever it blocks, so you can run one per request, even millions, with ordinary blocking code.

// Java 21
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    IntStream.range(0, 10_000).forEach(i ->
        executor.submit(() -> fetchOrder(i)));   // each task waits on I/O
}

In my test, 10,000 one-second blocking tasks took about 50 s on a 200-thread pool and about 1.1 s with virtual threads. The full before-and-after story, including pinning and when not to use them: Java 21 virtual threads explained.

2. Record patterns

Records (standard since Java 16) are one-line, immutable data classes. Java 21 lets you deconstruct them: check the type and pull out the components in one step.

record Point(int x, int y) {}

if (obj instanceof Point(int x, int y)) {
    System.out.println(x + y);   // no cast, no accessor calls
}

Patterns nest, too: Circle(Point(var x, var y), int radius) matches a circle and unpacks its centre in one go.

3. Pattern matching for switch

switch can now test types, not just constants, with optional when guards and an explicit case null:

String describe(Object obj) {
    return switch (obj) {
        case null                    -> "nothing";
        case Integer i when i > 1000 -> "big number";
        case Integer i               -> "number " + i;
        case String s                -> "text of length " + s.length();
        default                      -> "something else";
    };
}

Combined with sealed interfaces (Java 17), the compiler checks that a switch covers every case, so adding a new subtype breaks the build instead of production. Full guide: pattern matching for switch, and sealed classes.

4. Sequenced collections

Getting the last element of a List used to mean list.get(list.size() - 1), and a LinkedHashSet had no way to get its last element at all. Java 21 adds one set of methods to every ordered collection:

List<String> list = new ArrayList<>(List.of("a", "b", "c"));
list.getFirst();     // "a"
list.getLast();      // "c"
list.addFirst("z");  // [z, a, b, c]
list.reversed();     // a reversed view: [c, b, a, z]

The same methods work on Deque, LinkedHashSet, TreeSet, and (as firstEntry(), putFirst() and friends) on LinkedHashMap and TreeMap. Full guide: Java 21 sequenced collections.

“Java 21 is the release where modern Java stopped being a list of previews and became the default way to write it.”

Runtime and security features

Generational ZGC. ZGC is Java’s low-pause garbage collector. Java 21 added a generational mode that collects short-lived objects more often, which reduces CPU and memory overhead. In Java 21 you opt in with -XX:+UseZGC -XX:+ZGenerational; in later versions generational is simply how ZGC works. Most services are fine on the default G1 collector, so try ZGC when pause times matter.

Key Encapsulation Mechanism (KEM) API. A standard javax.crypto.KEM API for modern key-exchange schemes, a building block for future-proof (including post-quantum) cryptography.

Dynamic agent warning. Loading a Java agent into an already-running JVM now prints a warning, as a first step toward disallowing it by default. Agents passed on the command line with -javaagent are unaffected.

The preview features, and what happened to them

Java 21 also previewed several features. Here’s where each one ended up, as of Java 26:

  • String templates (STR."Hello \{name}"): previewed in 21 and 22, then withdrawn in Java 23 for a redesign. If you see this syntax in an old tutorial, it doesn’t compile in current Java.
  • Unnamed patterns and variables: lets you write _ for things you don’t use, like catch (Exception _) or case Point(var x, _). Final in Java 22.
  • Unnamed classes and instance main methods: write void main() { ... } with no class around it, for scripts and beginners. Finalised in Java 25 as “compact source files and instance main methods”.
  • Scoped values: an immutable, safer alternative to ThreadLocal that works well with virtual threads. Final in Java 25.
  • Structured concurrency: treat a group of related tasks as one unit, so if one fails the others are cancelled. Still a preview (sixth round) in Java 26.
  • Foreign Function & Memory API: call native libraries and manage off-heap memory without JNI. Final in Java 22.

Small API additions you’ll actually use

Not every useful change gets a JEP. A few that landed in Java 21:

new StringBuilder().repeat("ab", 3);              // "ababab"
Math.clamp(150, 0, 100);                          // 100
Character.isEmoji("😀".codePointAt(0));           // true
"a,b;c".splitWithDelimiters("[,;]", 0);           // [a, ",", b, ";", c]
"hello".indexOf('l', 0, 3);                       // 2: search within a range

Older features you’ll use alongside Java 21

If you’re coming from Java 8 or 11, these arrived between then and Java 21 and show up in nearly every Java 21 codebase:

Feature Since Guide
var for local variables Java 10 Java var explained
Switch expressions (case X ->) Java 14 Pattern matching for switch
Text blocks (""") Java 15 Java text blocks
Records Java 16 Java records explained
Pattern matching for instanceof Java 16 Pattern matching for switch
Sealed classes Java 17 Java sealed classes

Upgrading from Java 17 to Java 21

Java 21 is a smooth upgrade for most applications, but check these:

  • UTF-8 is the default charset (since Java 18). Code that read or wrote files without naming a charset used to follow the operating system’s setting (often not UTF-8 on Windows). Now it’s UTF-8 everywhere. Usually a fix, but test file and console I/O.
  • Frameworks. Use Spring Boot 3.2 or later to get virtual-thread support with one property (spring.threads.virtual.enabled=true). Update build plugins, Lombok, Mockito and bytecode tools to versions that support Java 21.
  • Deprecated APIs. Thread.stop(), finalization and the Security Manager have been heading out for several releases. Compile with -Xlint:deprecation and fix the warnings.
  • Agents. If a monitoring tool attaches to a running JVM, expect the new warning; add -XX:+EnableDynamicAgentLoading if you need it to stay quiet.

Key takeaways

  • Java 21 is an LTS release (September 2023) and a common production baseline.
  • Four features change everyday code: virtual threads, record patterns, pattern matching for switch and sequenced collections.
  • Previews need --enable-preview and can change: string templates were withdrawn, while scoped values and the unnamed _ became final later.
  • Upgrading from 17: watch the UTF-8 default, update frameworks and tools, and clear deprecation warnings.

Frequently asked questions

What are the main features of Java 21?

Virtual threads, record patterns, pattern matching for switch, sequenced collections, generational ZGC and a key encapsulation API are the final features. String templates, unnamed variables, scoped values, structured concurrency and instance main methods were previews.

Is Java 21 an LTS version?

Yes. Java 21 is a long-term-support release, following Java 17. The next LTS after it is Java 25.

When was Java 21 released?

Java 21 became generally available on 19 September 2023.

Are virtual threads production-ready in Java 21?

Yes. Virtual threads are a final, standard feature in Java 21 (JEP 444), not a preview. Watch for pinning inside synchronized blocks, which Java 24 later fixed.

Should I upgrade from Java 17 to Java 21?

For most teams, yes: it’s a straightforward upgrade with real gains, especially virtual threads for I/O-heavy services and pattern matching for cleaner code. Test file I/O for the UTF-8 default and update your frameworks first.

Start the deep dives with virtual threads, or see how records, sealed classes and pattern matching fit together.

Comments

LEAVE A COMMENT
No sign-up. Comments appear after a quick review.