Finalized in Java 21 LTS (Project Loom), Virtual Threads represent the most profound evolution in Java concurrency since the language's inception. They allow high-throughput web servers and microservices to run millions of concurrent connections using simple, synchronous code without complex reactive programming.
Figure 12: Architectural Mapping: Millions of lightweight Virtual Threads scheduled onto a small pool of OS Carrier Threads.
import java.util.concurrent.Executors;
import java.time.Duration;
public class VirtualThreadDemo {
public static void main(String[] args) throws Exception {
// 1. Spawning a single virtual thread
Thread vThread = Thread.ofVirtual().name("VThread-1").start(() -> {
System.out.println("Running inside: " + Thread.currentThread());
});
vThread.join();
// 2. Launching 100,000 Concurrent Virtual Threads with Ease!
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 1; i <= 100_000; i++) {
final int taskId = i;
executor.submit(() -> {
Thread.sleep(Duration.ofMillis(500)); // Non-blocking sleep!
return taskId;
});
}
} // Automatically awaits completion of all 100,000 tasks!
System.out.println("Successfully executed 100,000 virtual threads without crashing RAM!");
}
}
Congratulations on completing Concurrency! Let us now enter Section 7: File I/O, NIO.2 & JVM Internals. Proceed to: Java File I/O Streams →
Accelerate your Java mastery by studying these tightly connected core tutorials:
Virtual thread executors.
Platform threads comparison.
JVM execution engine.
Entering Section 7: File I/O.