JDK 21 Features
π Table of Contents
- What is JDK 21
- Why JDK 21 Matters
- Virtual Threads (Project Loom)
- Structured Concurrency
- Scoped Values
- Pattern Matching for Switch (Final)
- Record Patterns
- Sequenced Collections
- String Templates (Preview)
- Summary
- Interview Questions
π€ What is JDK 21?
JDK 21 is a Long-Term Support (LTS) release of Java.
π That means:
- It will be supported for years
- Production-ready features
- Major improvements in concurrency and language design
π‘ Why JDK 21 is Important
Before JDK 21:
β οΈ Threads were expensive
β οΈ Async code was complex (CompletableFuture hell π
)
β οΈ Pattern matching was limited
JDK 21 fixes these problems in a very elegant way.
π§΅ 1. Virtual Threads (Project Loom)
This is the biggest feature.
π Problem
Traditional threads (platform threads):
- Heavyweight
- Limited (~thousands max)
- Expensive context switching
π Solution
Virtual Threads:
- Lightweight
- Managed by JVM, not OS
- You can create millions of them
π§ Internal Working
π Virtual threads are scheduled by the JVM using carrier threads (actual OS threads)
Think of it like:
- Many virtual threads β mapped onto few OS threads
- JVM handles scheduling instead of OS
β Example
public class VirtualThreadExample {
public static void main(String[] args) throws Exception {
Runnable task = () -> {
System.out.println("Running in: " + Thread.currentThread());
};
Thread.startVirtualThread(task);
Thread.sleep(1000);
}
}
π Output shows something like:
VirtualThread[#21]/runnable@ForkJoinPool
π₯ Real Use Case
Handling thousands of API calls:
try (var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10000; i++) {
executor.submit(() -> {
System.out.println("Task executed by: " + Thread.currentThread());
});
}
}
π‘ No more thread pool tuning headache.
π§΅ 2. Structured Concurrency (Preview)
This feature changes how we manage parallel tasks.
π Problem
When multiple threads run:
- Hard to manage lifecycle
- Error handling becomes messy
π Solution
Structured Concurrency groups tasks together.
π§ Internal Idea
π Treat multiple threads like a single unit of work
If one fails:
- Cancel others
- Propagate error cleanly
β Example
import java.util.concurrent.*;
public class StructuredConcurrencyExample {
public static void main(String[] args) throws Exception {
try (var scope = new StructuredTaskScope.ShutdownOnFailure()) {
Future<String> task1 = scope.fork(() -> "Result 1");
Future<String> task2 = scope.fork(() -> "Result 2");
scope.join();
scope.throwIfFailed();
System.out.println(task1.resultNow());
System.out.println(task2.resultNow());
}
}
}
π‘ Cleaner than CompletableFuture chains.
π 3. Scoped Values (Preview)
π Problem
ThreadLocal:
- Hard to manage
- Memory leaks risk
- Debugging nightmare
π Solution
Scoped Values provide immutable thread-bound data
π§ Internal Concept
π Values are:
- Immutable
- Bound to execution scope
- Automatically cleaned
β Example
import java.lang.ScopedValue;
public class ScopedValueExample {
static final ScopedValue<String> USER = ScopedValue.newInstance();
public static void main(String[] args) {
ScopedValue.where(USER, "Amit").run(() -> {
System.out.println(USER.get());
});
}
}
π‘ Much safer than ThreadLocal.
π 4. Pattern Matching for Switch (Final)
Finally stable π
π Before
if (obj instanceof String) {
String s = (String) obj;
}
π Now
static void test(Object obj) {
switch (obj) {
case String s -> System.out.println("String: " + s);
case Integer i -> System.out.println("Integer: " + i);
default -> System.out.println("Unknown");
}
}
π§ Internal Benefit
π Compiler ensures:
- Exhaustiveness
- Type safety
- Less casting
π¦ 5. Record Patterns
Records become even more powerful.
β Example
record Person(String name, int age) {}
public class RecordPatternExample {
static void print(Object obj) {
if (obj instanceof Person(String name, int age)) {
System.out.println(name + " is " + age);
}
}
}
π‘ Direct destructuring of objects.
π 6. Sequenced Collections
Finally, Java standardizes order-aware collections.
π New Interfaces
- SequencedCollection
- SequencedSet
- SequencedMap
β Example
import java.util.*;
public class SequencedExample {
public static void main(String[] args) {
SequencedCollection<String> list = new ArrayList<>();
list.add("A");
list.add("B");
System.out.println(list.getFirst());
System.out.println(list.getLast());
}
}
π§ Why It Matters
π Before:
- No consistent way to access first/last
π Now:
- Unified API across collections
π§ͺ 7. String Templates (Preview)
Safer and cleaner string building.
π Problem
String query = "SELECT * FROM users WHERE id = " + userId;
β οΈ Risk of injection
String name = "John";
String message = STR."Hello \{name}";
π§ Internal Idea
π Template processors validate and transform strings safely.
β Summary
JDK 21 is not just an upgrade β itβs a shift.
π Key takeaways:
- Virtual Threads β Massive scalability
- Structured Concurrency β Cleaner parallel code
- Scoped Values β Safer context handling
- Pattern Matching β Better readability
- Record Patterns β Simpler data handling
- Sequenced Collections β Consistent APIs
- String Templates β Safer string operations
π― Interview Questions
1. What are Virtual Threads?
π Lightweight threads managed by JVM for high scalability.
2. Difference between Virtual Thread and Platform Thread?
π Virtual β JVM managed
π Platform β OS managed
3. What is Structured Concurrency?
π Managing multiple tasks as a single unit.
4. Why Scoped Values over ThreadLocal?
π Immutable, safer, no memory leaks.
5. What is Pattern Matching in switch?
π Type-based branching with automatic casting.
6. What are Record Patterns?
π Destructuring objects directly in conditions.
7. What are Sequenced Collections?
π Collections with defined ordering operations.
