Cosmic Module

J

Qubits of DPK

March 14, 2026

Core Java

Why JDK 21 Matters

JDK 21 is a Long-Term Support (LTS) release — the most important Java release since Java 11. Every major production system will eventually migrate to Java 21. MAANG interviews increasingly ask about these features.

1️⃣ Virtual Threads (Project Loom) — Biggest Feature

The Problem with Traditional Threads

javascript
QUBITS OF DPK
1Traditional Thread = OS Thread
23├── Heavy: 1-2MB memory per thread
4├── Expensive to create/destroy
5├── OS limit: typically 1000-10000 threads max
6└── Blocking I/O wastes OS thread (thread idles waiting)
7
8Problem: A server handling 10,000 concurrent requests
9need 10,000 threads = 10-20GB memory!

Virtual Threads Solution

java
QUBITS OF DPK
1// Traditional thread — heavy OS thread
2Thread t = new Thread(() -> handleRequest());
3t.start();
4
5// Virtual thread — lightweight, managed by JVM!
6Thread vt = Thread.ofVirtual().start(() -> handleRequest());
7
8// Create millions of virtual threads!
9try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
10    for (int i = 0; i < 1_000_000; i++) {
11        executor.submit(() -> handleRequest());
12    }
13}
14// 1 MILLION virtual threads — no problem!

How Virtual Threads Work

javascript
QUBITS OF DPK
1Virtual Threads are multiplexed onto a small pool of OS threads
2
3OS Threads (carrier threads): e.g., 8 (one per CPU core)
4Virtual Threads: millions!
5
6When virtual thread blocks on I/O:
7JVM unmounts it from carrier thread
8Carrier thread picks up another virtual thread
9When I/O completes, virtual thread gets remounted
10
11Result: No wasted OS threads during blocking!

Real Impact

javascript
QUBITS OF DPK
1Before Java 21 (Spring Boot with traditional threads):
2Server: 500 concurrent requests max (limited by thread pool)
3
4Java 21 (with virtual threads):
5Same server: 100,000+ concurrent requests
6No code change needed (Spring Boot 3.2+ enables automatically!)

2️⃣ Pattern Matching for switch (Java 21 — Stable)

java
QUBITS OF DPK
1// Before Java 21 — instanceof chains
2Object obj = "Hello";
3
4if (obj instanceof String s) {
5    System.out.println(s.toUpperCase());
6} else if (obj instanceof Integer i) {
7    System.out.println(i * 2);
8} else if (obj instanceof Double d) {
9    System.out.println(d + 1.0);
10}
11
12// Java 21 — Pattern matching switch (clean!)
13String result = switch (obj) {
14    case String s  -> s.toUpperCase();
15    case Integer i -> String.valueOf(i * 2);
16    case Double d  -> String.valueOf(d + 1.0);
17    case null      -> "null value";
18    default        -> "unknown: " + obj;
19};

Guarded Patterns

java
QUBITS OF DPK
1Object obj = 42;
2
3String result = switch (obj) {
4    case Integer i when i > 100 -> "Large number: " + i;
5    case Integer i when i > 0   -> "Positive: " + i;
6    case Integer i              -> "Non-positive: " + i;
7    default                     -> "Not an integer";
8};
9// Output: Positive: 42

3️⃣ Sequenced Collections

java
QUBITS OF DPK
1// New interfaces: SequencedCollection, SequencedSet, SequencedMap
2// Consistent first/last element access across all collections
3
4List<String> list = new ArrayList<>(List.of("a", "b", "c"));
5
6// New methods
7list.getFirst();   // "a" — previously: list.get(0)
8list.getLast();    // "c" — previously: list.get(list.size()-1)
9list.addFirst("z"); // add to front
10list.addLast("d");  // add to end
11list.removeFirst(); // remove from front
12list.removeLast();  // remove from end
13list.reversed();    // reversed view
14
15// Works for LinkedList, ArrayDeque, TreeSet, LinkedHashMap too!

4️⃣ String Templates (Preview in Java 21)

java
QUBITS OF DPK
1// Traditional string formatting
2String name = "Deepak";
3int age = 25;
4String msg = "Hello, " + name + "! You are " + age + " years old.";
5
6// String template (Java 21 preview)
7String msg = STR."Hello, \{name}! You are \{age} years old.";
8// Output: Hello, Deepak! You are 25 years old.
9
10// Multi-line
11String json = STR."""
12    {
13        "name": "\{name}",
14        "age": \{age}
15    }
16    """;

5️⃣ Record Patterns (Java 21)

java
QUBITS OF DPK
1record Point(int x, int y) { }
2record Circle(Point center, double radius) { }
3
4Object shape = new Circle(new Point(1, 2), 5.0);
5
6// Destructure record components directly in pattern matching!
7if (shape instanceof Circle(Point(int x, int y), double r)) {
8    System.out.println("Center: " + x + "," + y + " Radius: " + r);
9}
10// Output: Center: 1,2 Radius: 5.0

JDK 21 Features Summary

30-Second Interview Answer

"JDK 21 is the latest LTS release with several landmark features. Virtual Threads (Project Loom) are lightweight JVM-managed threads that solve the scalability problem — you can create millions of them since they multiplex onto a small OS thread pool, dramatically improving throughput for I/O-bound applications without code changes. Pattern matching for switch became stable, enabling clean type-based dispatch with guarded patterns using 'when'. Sequenced Collections added first/last access methods uniformly across all collections. Record patterns allow destructuring record components directly in instanceof and switch patterns."

Interview Questions & MAANG-Level Answers

Q1. What are Virtual Threads and how are they different from platform threads?
Platform (OS) threads: mapped 1-to-1 to OS threads, heavy (1-2MB stack memory), expensive to create, OS limits typically 10K-50K max. Virtual threads (Java 21, Project Loom): lightweight JVM-managed threads, tiny memory footprint (few KB), create millions of them, multiplexed onto a small pool of carrier (OS) threads. When a virtual thread blocks on I/O, JVM unmounts it from the carrier thread (which picks up another virtual thread) and remounts it when I/O completes. No wasted OS threads during blocking.
Q2. How do Virtual Threads improve server scalability?
Traditional thread-per-request model: each HTTP request gets an OS thread — 500 thread pool = 500 max concurrent requests. Virtual threads allow millions of threads: each request gets its own virtual thread, blocked I/O (DB calls, API calls) releases the carrier thread for other work. A server that handled 500 concurrent requests can now handle 100,000+ with the same hardware. No code change needed — Spring Boot 3.2+ enables virtual threads with one config line: spring.threads.virtual.enabled=true.
Q3. What is pattern matching for switch in Java 21?
Allows switching on an Object with type patterns, replacing chains of if-instanceof:
java
QUBITS OF DPK
1String describe(Object obj) {
2    return switch (obj) {
3        case Integer i -> "int: " + i;
4        case String s  -> "string: " + s;
5        case null      -> "null";
6        default        -> "other";
7    };
8}
The JVM performs a single dispatch rather than sequential instanceof checks. Combined with sealed classes, the compiler verifies exhaustiveness. This is a fundamental shift toward functional-style programming in Java.
Q4. What are guarded patterns?
Guarded patterns add a condition (when clause) to a type pattern in switch:
java
QUBITS OF DPK
1switch (obj) {
2    case Integer i when i > 100 -> "large integer";
3    case Integer i when i > 0   -> "positive integer";
4    case Integer i              -> "non-positive integer";
5    default                     -> "not an integer";
6}
Cases are checked top-to-bottom — first matching case wins. when guards allow fine-grained control beyond just type matching, without needing nested if statements inside cases.
Q5. What is Project Loom?
Project Loom is the OpenJDK project that introduced Virtual Threads into Java (delivered in Java 21 as stable). It aimed to make concurrency simpler by allowing the simple thread-per-task programming model to scale like reactive/async code without the complexity. Key deliverable: Virtual Threads. Secondary deliverable: Structured Concurrency (preview) — managing groups of related virtual threads as a unit for better error propagation and cancellation.
Q6. What are Sequenced Collections?
New interfaces in Java 21 (JEP 431) that provide consistent first/last access across ordered collections:
java
QUBITS OF DPK
1List<String> list = new ArrayList<>(List.of("a", "b", "c"));
2list.getFirst();    // "a" — was: list.get(0)
3list.getLast();     // "c" — was: list.get(list.size()-1)
4list.reversed();    // reversed view
Solves inconsistency: List had get(0), Deque had peekFirst(), SortedSet had first() — all doing the same thing differently. Now: SequencedCollection interface standardizes this across List, LinkedHashSet, ArrayDeque, and TreeSet.
Q7. What is a record pattern?
Record patterns (Java 21) allow destructuring record components directly in instanceof and switch:
java
QUBITS OF DPK
1record Point(int x, int y) {}
2record Circle(Point center, double radius) {}
3
4if (shape instanceof Circle(Point(int x, int y), double r)) {
5    System.out.println("Center: " + x + "," + y);  // x,y extracted!
6}
7
8// In switch
9switch (shape) {
10    case Circle(Point(int x, int y), double r) when r > 10 ->
11        "Large circle at " + x + "," + y;
12    default -> "Other";
13}
Nested record patterns extract deeply nested components in a single expression — eliminates chained accessor calls.