Java 21 Features
Java 21 Key Features (LTS)
Java 21 is a Long-Term Support (LTS) release (after Java 17), focusing on concurrency, pattern matching, and developer productivity.
1. Virtual Threads (Final ) — Most Important
What problem it solves?
Traditional threads are heavy (OS threads) → limits scalability.
Solution
Lightweight threads managed by JVM → millions of threads possible
Example
try (var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 100_000; i++) {
executor.submit(() -> {
System.out.println(Thread.currentThread());
});
}
}Key Points
- Used for high-concurrency apps (microservices, APIs)
- No thread pooling needed
- Works seamlessly with existing Java code
Interview line:
Virtual threads enable high scalability by significantly reducing the cost of thread creation compared to platform threads.
2. Structured Concurrency (Preview)
Purpose
Manage multiple threads as a single unit
Example
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<String> user = scope.fork(() -> getUser());
Future<String> order = scope.fork(() -> getOrder());
scope.join(); // wait all
scope.throwIfFailed(); // handle failure
System.out.println(user.resultNow() + order.resultNow());
}Benefits
- Better error handling
- Cleaner concurrent code
- Parent-child task relationship
3. Record Patterns (Final)
Purpose
Destructure objects directly
Example
record Person(String name, int age) {}
static void print(Object obj) {
if (obj instanceof Person(String name, int age)) {
System.out.println(name + " " + age);
}
}With nested records
record Address(String city) {}
record Employee(String name, Address addr) {}
if (obj instanceof Employee(String name, Address(String city))) {
System.out.println(city);
}Key Advantage
- Cleaner data extraction
- Reduces boilerplate getters
4. Pattern Matching for switch (Final)
Powerful upgrade of switch
Example
static String check(Object obj) {
return switch (obj) {
case Integer i -> "Integer: " + i;
case String s -> "String: " + s;
case null -> "Null value";
default -> "Unknown";
};
}With guards
case Integer i when i > 100 -> "Large number";Benefits
- Type-safe
- No casting needed
- Supports null handling
5. Sequenced Collections (Final)
Purpose
Uniform API for ordered collections
Get Syed Nazeer’s stories in your inbox
Join Medium for free to get updates from this writer.
New interfaces
SequencedCollectionSequencedSetSequencedMap
Example
SequencedCollection<Integer> list = new ArrayList<>();
list.addFirst(1);
list.addLast(2);
System.out.println(list.getFirst()); // 1
System.out.println(list.getLast()); // 2Benefit
- Works across List, Set, Map
- First/last operations standardized
6. String Templates (Preview)
Purpose
Better string formatting than concatenation
Example
String name = "Nazeer";
String str = STR."Hello {name}";Advanced
int a = 10, b = 20;
String result = STR."{a} + {b} = {a + b}";---### Benefit
- Cleaner than `+`
- Safer than `String.format()`---# 7. Unnamed Patterns & Variables (Preview)### Purpose
Ignore unwanted variables---### Example```java
if (obj instanceof Person(_, int age)) {
System.out.println(age);
}
Loop example
for (var _ : list) {
System.out.println("Ignoring value");
}8. Foreign Function & Memory API (Final)
Purpose
Access native memory safely (replacement for JNI)
Example
MemorySegment segment = MemorySegment.allocateNative(100);Benefits
- Safer than JNI
- High-performance IO operations
9. Scoped Values (Preview)
Purpose
Immutable thread-local alternative
Example
static final ScopedValue<String> USER = ScopedValue.newInstance();
ScopedValue.where(USER, "Nazeer").run(() -> {
System.out.println(USER.get());
});Benefit
- Better than ThreadLocal
- Works well with virtual threads
10. ZGC & G1 Improvements
Enhancements
- Lower pause times
- Better memory usage
- Improved performance
Quick Summary Table
Interview Summary (Must Say)
Java 21 focuses on scalability and clean code. Virtual Threads revolutionize concurrency by enabling lightweight thread creation. Pattern Matching and Record Patterns simplify data handling. Structured Concurrency improves multi-threading readability, while Sequenced Collections standardize APIs.







