Java 21 features developers actually use

The Java 21 LTS features that change everyday code: virtual threads, pattern matching for switch, record patterns, sequenced collections and new String and Math methods, with examples and upgrade notes.

Written for JDK 21 LTS

Java 21 was released on 19 September 2023 and is a long-term support release, which is why so many projects moved straight from Java 17 to it. It shipped 15 JEPs, but a handful of them change how everyday code looks. This tutorial goes through those with examples, separates the finished features from the previews, and ends with what you need to change in your build to upgrade.

The release at a glance

FeatureJEPStatus in 21
Virtual threads444Final
Pattern matching for switch441Final
Record patterns440Final
Sequenced collections431Final
Generational ZGC439Final, opt-in
Key encapsulation mechanism API452Final
Unnamed patterns and variables443Preview (final in 22)
Unnamed classes and instance main methods445Preview
String templates430Preview (later removed)
Scoped values, structured concurrency446, 453Preview
Foreign function and memory API442Third preview (final in 22)

Everything marked final works with a plain javac and java. Previews need --enable-preview, can change between releases, and are best kept out of production code.

Virtual threads

Virtual threads are the headline feature. A platform thread maps to an operating system thread, and a server runs out of those at a few thousand. A virtual thread is managed by the JVM and keeps its stack on the heap, so an idle one costs little memory and you can run one per request, or one per task, even with a million tasks. When a virtual thread blocks on I/O, the JVM parks it and reuses the underlying carrier thread for other work.

The simplest way in is an executor that starts a new virtual thread per task:

Java
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
    IntStream.range(0, 10_000).forEach(i ->
        executor.submit(() -> {
            Thread.sleep(Duration.ofSeconds(1));
            return i;
        }));
} // close() waits for all tasks to finish

Ten thousand tasks that each sleep for a second finish in about one second, because sleeping (like waiting on a socket) does not hold an OS thread. You can also start one directly with Thread.startVirtualThread(runnable) or name them with Thread.ofVirtual().name("worker-", 0).start(runnable).

What changes in practice:

  • Write plain blocking code. The point of virtual threads is that HttpClient.send, JDBC calls and Thread.sleep no longer need to be wrapped in callbacks or reactive types to scale.
  • Do not pool virtual threads. They are cheap to create; a pool only limits them. If you need to cap concurrency, for example to 20 database connections, use a Semaphore.
  • They help with waiting, not with computing. CPU-heavy work runs no faster on virtual threads.
  • In JDK 21, a virtual thread that blocks inside a synchronized block stays pinned to its carrier thread, which can starve the scheduler under load. Use ReentrantLock around blocking calls in hot paths. JDK 24 removed this limitation (JEP 491).

In Spring Boot 3.2 and newer, setting spring.threads.virtual.enabled=true runs request handling on virtual threads without other code changes.

Pattern matching for switch

switch can now match on types, not only on constants, and bind a variable in the same step. Combined with sealed interfaces, the compiler checks that you handled every case:

Java
sealed interface Payment permits Card, BankTransfer, Voucher {}
record Card(String last4, YearMonth expiry) implements Payment {}
record BankTransfer(String iban) implements Payment {}
record Voucher(String code, BigDecimal value) implements Payment {}

static String describe(Payment payment) {
    return switch (payment) {
        case Card c when c.expiry().isBefore(YearMonth.now()) -> "expired card ending " + c.last4();
        case Card c -> "card ending " + c.last4();
        case BankTransfer t -> "transfer from " + t.iban().substring(0, 4) + "...";
        case Voucher v -> "voucher worth " + v.value();
    };
}

The when clause is a guard: the first Card case only matches expired cards. Order matters, so the more specific case comes first; the compiler rejects a case that can never be reached. There is no default, because Payment is sealed and all three types are covered. Add a fourth payment type later and this method stops compiling until you handle it, which is exactly the reminder you want.

A switch on a reference type can also handle null explicitly with case null ->; without it, a null selector still throws NullPointerException as before.

Record patterns

Record patterns take a record apart in the pattern itself, and they nest:

Java
record Point(int x, int y) {}
record Line(Point from, Point to) {}

static boolean isVertical(Object obj) {
    return obj instanceof Line(Point(var x1, var y1), Point(var x2, var y2)) && x1 == x2;
}

They work in instanceof and in switch cases. The Java records tutorial has a longer example with a sealed shape hierarchy, plus the basics of records themselves.

Sequenced collections

Java finally has one way to get the first and last element of an ordered collection. Before 21, it was list.get(0) and list.get(list.size() - 1) for lists, deque.peekFirst() for deques, and an iterator loop for a LinkedHashSet. Three new interfaces, SequencedCollection, SequencedSet and SequencedMap, add the same methods to all of them:

Java
List<String> steps = new ArrayList<>(List.of("plan", "build", "ship"));
steps.getFirst();      // "plan"
steps.getLast();       // "ship"
steps.addFirst("idea");
steps.reversed();      // [ship, build, plan, idea], a reversed view

LinkedHashMap<String, Integer> scores = new LinkedHashMap<>();
scores.put("ada", 3);
scores.put("bob", 5);
scores.firstEntry();   // ada=3
scores.putFirst("cy", 1);
scores.pollLastEntry(); // removes and returns bob=5

reversed() returns a view, not a copy, so changes show through in both directions. On an unmodifiable list such as List.of(...), addFirst throws UnsupportedOperationException, as add always has.

Smaller additions worth knowing

Some new methods replace helpers that many projects carried around:

Java
Math.clamp(value, 0, 100);              // keeps value within 0..100
new StringBuilder().repeat("-", 40);    // forty dashes
"a,b;c".splitWithDelimiters("[,;]", 0); // [a, ",", b, ";", c]
Character.isEmoji(codePoint);           // emoji checks for code points

HttpClient now implements AutoCloseable, so a client created for a batch job can live in a try-with-resources block.

Generational ZGC keeps separate young and old generations, which lowers the overhead of the low-pause ZGC collector for most applications. In JDK 21 you opt in with -XX:+UseZGC -XX:+ZGenerational; later releases made the generational mode the default.

JDK 21 also prints a warning when an agent is loaded into an already running JVM (JEP 451). If you use a tool that attaches that way, add -XX:+EnableDynamicAgentLoading to keep the current behaviour without the warning.

The previews, briefly

Unnamed patterns and variables let you write _ for a value you must declare but never use, such as catch (NumberFormatException _). This became final in Java 22. Unnamed classes and instance main methods let a beginner's first program be just void main() { System.out.println("Hello"); }; the idea was reworked in later releases. String templates were previewed in 21 and 22 and then removed, so they are not part of Java today. If you try a preview, compile and run with --enable-preview --release 21, and expect to change the code when you move to a newer JDK.

Upgrading a project to Java 21

Set the release level in your build, which also makes javac reject APIs newer than the target:

pom.xml
<properties>
    <maven.compiler.release>21</maven.compiler.release>
</properties>

In Gradle, a toolchain downloads or selects the right JDK for you:

build.gradle.kts
java {
    toolchain {
        languageVersion = JavaLanguageVersion.of(21)
    }
}

Then update the tools that read bytecode, because old versions fail on Java 21 class files: Lombok, Mockito and Byte Buddy, Jacoco, and the Maven Surefire and Gradle versions themselves. Most "unsupported class file major version 65" errors come from one of those; 65 is the class file version for Java 21.

Java 21 remains a sensible baseline for production. JDK 25, released in September 2025, is the next LTS release. The full list of changes is on the JDK 21 project page, and the virtual thread design is explained in JEP 444.

About Glenna Babshire29 Articles
Java & libraries writer. Writes the Java tutorials: the language from Java 21 on, encryption, configuration and the libraries around it.