skip to content

What did Java 21 bring over Java 17 for a working Java developer?

level: middleimportance: must knowfreq 76%

answer

  1. thread-per-request scales again
  2. scale, not speed
  3. the compiler checks every case
  4. first and last, at last
  5. a charset default changed at 18

basics

~20 s

Java 21 made virtual threads, pattern matching for switch, record patterns and sequenced collections final, and added generational ZGC as an option. On the way, Java 18 made UTF-8 the default charset, which can change behaviour on upgrade.

solid answer

~40 s

The headline is virtual threads, final at 21 after previews in 19 and 20. They let plain blocking thread-per-request code handle far more concurrent tasks. They add scale, not speed, so they do not help CPU-heavy work. The second is pattern matching for `switch` with record patterns: over a sealed type, a `switch` with no `default` is checked by the compiler, so adding a subtype breaks the build where it should. `SequencedCollection` adds `getFirst`, `getLast` and `reversed`. Check two things on upgrade: UTF-8 became the default charset in Java 18, and generational ZGC needs an extra flag at 21. Scoped values, structured concurrency and string templates were only previews at 21.

code

java · 30 lines
java
import java.util.concurrent.Executors;
import java.util.stream.IntStream;

public class Java21Idioms {
    sealed interface Shape permits Circle, Rect {}

    record Circle(double r) implements Shape {}

    record Rect(double w, double h) implements Shape {}

    static double area(Shape shape) {
        return switch (shape) {
            case Circle(double r) -> Math.PI * r * r;
            case Rect(double w, double h) when w == h -> w * w;
            case Rect(double w, double h) -> w * h;
        };
    }

    public static void main(String[] args) {
        System.out.println(area(new Rect(2, 3)));

        try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
            IntStream.range(0, 10_000).forEach(i -> executor.submit(() -> {
                Thread.sleep(100);
                return i;
            }));
        }
        System.out.println("all tasks finished");
    }
}

go deeper

for a junior

Recall the final features: virtual threads, pattern matching for switch, record patterns and sequenced collections. Be able to read a switch that uses a type pattern, and say what a virtual thread is.

for a middle

Explain the mechanics: carriers, what pinning means at 21, why a switch over a sealed type needs no default, and what MatchException means. Keep final and preview features apart.

for a senior

Show production judgment on adoption: which pools to replace, how to find pinning with Flight Recorder, what to do with thread-local caches, and how to test the charset change before an upgrade.

for a principal

Decide when the team moves. Weigh rewriting asynchronous code against keeping it now that blocking code scales, whether to wait for the synchronized fix at Java 24, and which libraries must be ready first.

## Virtual threads are the headline Java 21, released in September 2023, finalized virtual threads (JEP 444) after previews in Java 19 and 20. A **virtual thread** is a `java.lang.Thread` that the JDK schedules onto a small number of platform threads, called carriers. When it blocks on I/O or a lock, it usually gets out of the way and the carrier runs another virtual thread. What that means for working code: - **The point is scale.** Thread-per-request code stays simple and blocking, and the number of concurrent tasks is no longer limited by the cost of a platform thread. - **They are not faster.** JEP 444 says it directly: virtual threads do not run code any faster than platform threads. CPU-heavy work is still limited by the number of cores. - **Do not pool them.** Create one per task, for example with `Executors.newVirtualThreadPerTaskExecutor()`. If a pool was there to limit concurrent access to a resource, use a `Semaphore` instead. - **Pinning exists at 21.** Blocking inside a `synchronized` block or in a native frame keeps the carrier occupied. Java 24 removed the `synchronized` case (JEP 491), so 21 and 25 differ here. ## Pattern matching reaches switch | Feature | Previewed in | Final in | JEP | What it adds | |---|---|---|---|---| | Pattern matching for `switch` | 17, 18, 19, 20 | 21 | 441 | Type patterns in `case`, guards with `when`, and `case null` | | Record patterns | 19, 20 | 21 | 440 | Take a record apart in the pattern itself | Combined with the sealed classes finalized at Java 17, this delivers what those features were building towards. A `switch` over a sealed interface needs no `default` when it covers every permitted type. Add a new permitted type and the switch stops compiling, so the compiler finds every place that must change. Code that was not recompiled gets a `MatchException` at run time instead. ## Smaller additions you will meet - **Sequenced collections** (JEP 431) give ordered collections `getFirst`, `getLast` and `reversed`. They have their own question. - **`Math.clamp`** and **`StringBuilder.repeat`** (Java 21) cover small jobs that used to need helper code. - **`jwebserver`** (JEP 408, Java 18) serves static files from a directory. It is for testing, development and debugging only. - **`@snippet`** (JEP 413, Java 18) makes it simpler to include example source code in API documentation. ## What can change on upgrade - **UTF-8 by default** (JEP 400, Java 18). APIs that use the default charset, such as `new FileWriter(path)`, no longer depend on the operating system and locale. Text written or read without an explicit charset can change on a host that used another charset. `-Dfile.encoding=COMPAT` restores the old choice, and console output is not covered by the change. - **Generational ZGC** (JEP 439) is opt-in at 21: `-XX:+UseZGC -XX:+ZGenerational`. Java 23 made it the default mode and Java 24 removed the other mode. At 25 the extra flag is ignored with a warning, and at 27 the JVM refuses to start with it. - **Finalization** is deprecated for removal (JEP 421, Java 18), though it is still enabled by default. - **`Thread.stop`** throws `UnsupportedOperationException` from Java 20 through 25, and JDK 26 removed the method. - **Dynamically loaded agents** trigger a warning at 21 (JEP 451). Agents named at startup with `-javaagent` do not. ## What was not final at 21 This is where candidates slip, because all of these appeared in Java 21 announcements: - **Previews:** string templates (JEP 430), unnamed patterns and variables (JEP 443), unnamed classes and instance main methods (JEP 445), scoped values (JEP 446), structured concurrency (JEP 453) and the Foreign Function & Memory API (JEP 442). - **Incubating:** the Vector API (JEP 448). String templates never became final. After a second preview in Java 22 the feature was withdrawn, and Java 23 does not have it. The others became final later, or are still not final at JDK 27. ## How to answer Lead with virtual threads and say what you would and would not use them for. Then show the sealed-type and `switch` combination with a small example. Close with the charset change, because it shows you have thought about an upgrade and not only about the features.

  • Should you replace every thread pool with virtual threads when moving to Java 21?
    No. Replace pools that run many blocking tasks, using one virtual thread per task. Keep platform thread pools for CPU-heavy work, since virtual threads do not run code faster. If a pool also limited access to a resource, use a `Semaphore`. Check any thread-local that caches an expensive object, because it no longer gets reused.
  • What happens at run time if a sealed type gains a subtype but an old switch over it is not recompiled?
    The switch still runs against the new class, and when the new subtype reaches it, no label matches, so it throws `MatchException`. Recompiling turns that into a compile error instead, which is why a `switch` with no `default` is safer in code you build together.
  • How would you find out whether the UTF-8 default affects a service moving from Java 17 to 21?
    Look for APIs that use the default charset without an explicit argument, such as `new FileWriter(path)`, and compare `native.encoding` on your hosts with UTF-8. If they already match, little changes. If not, pass explicit charsets, or use `-Dfile.encoding=COMPAT` as a temporary measure.

A virtual thread is like a table in a restaurant and a carrier is like a waiter. The waiter leaves a table while the kitchen cooks, so a few waiters serve many tables. This adds no cooking speed, and a waiter held at one table serves nobody else, which is pinning.

  • Virtual threads run code faster than platform threads.
  • Virtual threads should be pooled, just like platform threads.
  • String templates are a final feature at Java 21.
  • Scoped values and structured concurrency became final at Java 21.
  • Generational ZGC is the default ZGC mode at Java 21.
  • At Java 21, a virtual thread is never pinned while inside synchronized.

Virtual threads
Java 21pre-release 19
Pattern matching for switch
Java 21pre-release 17
Record patterns
Java 21pre-release 19
Sequenced collections
Java 21
UTF-8 as the default charset
Java 18

Assumes JDK 27 as the baseline and compares Java 21 with Java 17; pinning in synchronized and the ZGC flag behave differently at Java 25, and the answer gives both.

context