Java 21 — Key Features
IntermediateJava 21 (LTS) delivers virtual threads, record patterns, sequenced collections, string templates preview, and finalised pattern matching.
Overview
Java 21 is a Long-Term Support (LTS) release packed with major features. Virtual threads (Project Loom) make thread-per-request servers scalable. Record patterns extend pattern matching to destructure records. Sequenced Collections add first/last access to ordered collections. Pattern matching for switch is finalised. String Templates (preview) enable safe, readable string interpolation. Together these make Java 21 one of the most significant releases since Java 8.
Virtual Threads and Sequenced Collections
Virtual threads (finalised JEP 444) are the headline feature — lightweight JVM-managed threads enabling millions of concurrent tasks with synchronous code style.
Sequenced Collections (JEP 431) adds SequencedCollection, SequencedSet, and SequencedMap interfaces with getFirst(), getLast(), addFirst(), addLast(), reversed() — filling a long-standing gap where you had to use different idioms for different collection types.
// Virtual threads — millions of concurrent I/O tasks
try (ExecutorService exec = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 100_000).forEach(i ->
exec.submit(() -> {
Thread.sleep(Duration.ofMillis(100)); // blocks, but no OS thread wasted
return processRequest(i);
}));
} // all 100,000 tasks complete, ~100ms total
// Sequenced Collections (Java 21 — JEP 431)
// SequencedCollection: List, Deque, LinkedHashSet
List<String> list = new ArrayList<>(List.of("a", "b", "c"));
list.getFirst(); // "a" (was: list.get(0))
list.getLast(); // "c" (was: list.get(list.size()-1))
list.addFirst("z"); // ["z","a","b","c"]
list.addLast("w"); // ["z","a","b","c","w"]
list.reversed(); // ["w","c","b","a","z"] view
// SequencedMap: LinkedHashMap
LinkedHashMap<String, Integer> map = new LinkedHashMap<>();
map.put("one", 1); map.put("two", 2); map.put("three", 3);
map.firstEntry(); // one=1
map.lastEntry(); // three=3
map.reversed(); // reversed order viewRecord Patterns and Pattern Matching
Record patterns (JEP 440, finalised) allow destructuring a record in an instanceof check or switch case. Combined with nested patterns, complex object graphs can be matched and destructured in one expression.
Pattern matching for switch (JEP 441, finalised) is complete — type patterns, guarded patterns (when), null handling, and exhaustiveness checks all work.
// Record patterns — destructure in instanceof
record Point(int x, int y) {}
record Circle(Point centre, double radius) {}
Object shape = new Circle(new Point(0, 0), 5.0);
// Destructure nested records in one pattern
if (shape instanceof Circle(Point(int x, int y), double r)) {
System.out.printf("Circle at (%d,%d) r=%.1f%n", x, y, r);
}
// Record patterns in switch
String describe(Object obj) {
return switch (obj) {
case Integer i when i < 0 -> "negative int: " + i;
case Integer i -> "positive int: " + i;
case String s when s.isEmpty() -> "empty string";
case String s -> "string: " + s;
case Point(int x, int y) -> "point (%d,%d)".formatted(x, y);
case Circle(Point(int x, int y), double r)
-> "circle at (%d,%d) r=%.1f".formatted(x,y,r);
case null -> "null";
default -> "unknown: " + obj.getClass().getSimpleName();
};
}String Templates (Preview) and Other Highlights
String Templates (JEP 430, preview in Java 21) provide safe, readable string interpolation. Unlike simple concatenation, template processors can validate and transform the embedded values — preventing injection attacks.
Other Java 21 highlights: Unnamed Classes and Instance Main Methods (preview — simpler "hello world"), Unnamed Patterns and Variables (preview — _ as discard), and the stabilisation of the Foreign Function & Memory API.
// String Templates (preview — enable with --enable-preview)
String name = "Alice";
double price = 99.99;
// STR processor — simple interpolation
String msg = STR."Hello, \{name}! Your total is \{price}.";
// "Hello, Alice! Your total is 99.99."
// FMT processor — formatted interpolation
String formatted = FMT."Price: %-10s\{name} $%,.2f\{price}";
// "Price: Alice $99.99"
// Custom processor — validates SQL (prevents injection)
// (Illustrative — real implementation would parameterise queries)
PreparedStatement ps = SQL."SELECT * FROM users WHERE id = \{userId}";
// Unnamed patterns (preview) — _ discards unwanted bindings
if (obj instanceof Point(int x, _)) {
System.out.println("x-coord: " + x); // don't care about y
}
// Switch discard
switch (shape) {
case Circle(_, double r) -> System.out.println("radius: " + r);
case _ -> System.out.println("other shape");
}
// Foreign Function & Memory API (finalised JEP 454)
// Call C libraries without JNI
try (Arena arena = Arena.ofConfined()) {
MemorySegment str = arena.allocateUtf8String("Hello");
// pass to native function...
}Key Points to Remember
- Virtual threads (JEP 444) finalised — use Executors.newVirtualThreadPerTaskExecutor().
- Sequenced Collections (JEP 431) adds getFirst/getLast/addFirst/addLast/reversed to ordered collections.
- Record patterns (JEP 440) allow destructuring records in instanceof and switch.
- Pattern matching for switch (JEP 441) finalised — type patterns, guards, null, exhaustiveness.
- String Templates (JEP 430) preview — interpolation with injection-safe template processors.
Practice Java 21 — Key Features in the Playground
Run and modify code directly in your browser - no setup needed.
Interview Questions
Sign in to ask AriaWhat are the major features of Java 21 LTS?
What are Sequenced Collections and what gap do they fill?
How do record patterns simplify working with nested data structures?
What is the difference between String Templates and simple String.format()?
How do virtual threads change the architecture of a high-concurrency Java server?
Ask Aria about Java 21 — Key Features
Your personal AI tutor — ask anything about this concept