Java Core & JVM (50 Qs)•Part 1: Core Language, Memory Model & Collections (1 - 10)
What are Virtual Threads in Java 21 (Project Loom), and how do they differ from Platform Threads?
junior LevelCode ExampleForms
In Simple Words:
- Platform Threads: 1:1 mapping to Operating System kernel threads. Heavy (~1MB stack), expensive to create, context switching requires OS kernel transition. A server with 5,000 idle platform threads can exhaust system memory.
- Virtual Threads: Lightweight user-space threads managed directly by the JVM (M:N mapping). Millions can run concurrently with tiny footprint (~few hundred bytes). When a virtual thread blocks on I/O (database, REST call), the JVM unmounts it from the carrier OS thread and mounts another virtual thread, maximizing throughput without reactive complexity.
java
// Java 21: Starting 10,000 concurrent Virtual Threads effortlessly:
try (var executor = java.util.concurrent.Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 10_000; i++) {
final int taskId = i;
executor.submit(() -> {
Thread.sleep(java.time.Duration.ofMillis(100)); // Non-blocking to carrier thread
return "Task " + taskId + " complete";
});
}
} // Auto-closes and awaits termination