Java / Java Concurrency and Multi Threading in Java 17 and Java 21 Interview questions
What is a virtual thread in Java 21?
A virtual thread is a lightweight thread implemented and scheduled entirely by the JVM rather than mapped one-to-one to an OS thread. It was delivered as a stable feature (JEP 444) in Java 21, the result of Project Loom.
Virtual threads run on top of a small pool of ordinary OS threads, called carrier threads. When a virtual thread performs a blocking operation like network I/O, the JVM unmounts it from its carrier so the carrier can run other virtual threads, then remounts it once the blocking operation completes.
Thread.ofVirtual().start(() -> handleRequest()); try (var executor = Executors.newVirtualThreadPerTaskExecutor()) { executor.submit(() -> handleRequest()); }
Because they're so cheap to create, an application can spin up millions of virtual threads, one per request or task, and keep writing simple blocking-style code instead of reactive or callback-based code, while still getting high throughput under I/O-bound load.
More Related questions...