What is Virtual Threads in Java (Project Loom)?
Answer
Virtual threads (Java 21, finalized) are lightweight threads managed by the JVM rather than the OS. Traditional Java threads are platform threads — each maps to an OS thread, which is expensive (1-2MB stack, OS scheduling overhead). Creating thousands of them is not practical. Virtual threads have a tiny memory footprint and are managed by the JVM on a small pool of carrier (OS) threads. When a virtual thread blocks (e.g., on I/O), it is unmounted from its carrier thread, which is then free to run other virtual threads. This makes the blocking, synchronous programming model as scalable as async/reactive code. Create them: Thread.ofVirtual().start(runnable) or Executors.newVirtualThreadPerTaskExecutor(). This is a game-changer for server applications that handle many concurrent blocking operations.