Java Core & JVM (50 Qs)•Part 3: JVM Internals, Low-Latency Systems & Production Tuning (25 - 35)
Java Virtual Threads (Project Loom): Architecture and Best Practices.
senior LevelCode ExampleSystem Design
In Simple Words:
Prior to Java 21, every java.lang.Thread was a heavyweight operating system (OS) kernel thread consuming $\approx 1\text{MB}$ of stack memory, limiting concurrency to a few thousand threads.
- Virtual Threads (
Thread.ofVirtual()): Lightweight user-mode threads managed entirely by the JVM:- Consumes only a few hundred bytes of heap memory; you can spawn 1,000,000+ virtual threads concurrently!
- Mounts onto a small pool of OS "carrier threads" (typically equal to CPU cores). When a virtual thread performs blocking I/O (database, socket, sleep), the JVM unmounts it from the carrier thread and parks it in heap memory, keeping the carrier thread 100% busy.
- Thread-per-request model: Eliminates reactive programming complexity (
WebFlux,Mono/Flux) while achieving identical non-blocking throughput.
java
// Spawning 100,000 Virtual Threads in Java 21+
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
IntStream.range(0, 100_000).forEach(i -> {
executor.submit(() -> {
Thread.sleep(Duration.ofSeconds(1)); // Unmounts from carrier thread; 0ms OS stall!
return i;
});
});
} // Blocks cleanly until all virtual threads finish