Learning Objectives
- Explain how JVM virtual threads mount and unmount cleanly onto OS carrier threads during blocking I/O.
- Identify when to choose virtual threads vs bounded platform pools vs async reactive stacks.
- Eliminate carrier thread pinning by preferring `ReentrantLock` over long `synchronized` I/O blocks on Java 21.
Prerequisites
- Java Multithreading fundamentals (`Runnable`, `ExecutorService`, `CompletableFuture`)
Why Platform Threads Hit a Scaling Wall
Traditional java.lang.Thread instances map 1:1 to heavyweight operating-system kernel threads (~1 MB default stack reserve plus expensive OS context switches). When a Tomcat service blocks waiting for PostgreSQL queries or downstream HTTP microservices, a 200-thread pool caps throughput artificially even while CPU cores sit largely idle.
Finalized in Java 21 LTS (JEP 444), Virtual Threads are lightweight JVM-managed continuations scheduled atop a small ForkJoinPool of OS carrier threads. Whenever a virtual thread hits a JDK blocking call (Socket, Thread.sleep, JDBC drivers on Java 21), the JVM unmounts its stack chunk to the heap so the carrier thread immediately executes another virtual thread.
Do Not Pool Virtual Threads
Unlike scarce platform threads, you never place virtual threads inside a fixed-size pool. Spawn one per unit of concurrent work with Executors.newVirtualThreadPerTaskExecutor() and use a Semaphore when you need concurrency backpressure against a database connection limit.
Put this directly into practice with our Spring Boot Dependency Injection Guide, practice Java Concurrency MCQs, or train live in the Java Backend Career Program.
Practical Programming Examples
Running 1,000 Concurrent I/O Tasks cleanly with Virtual Threads (JDK 21)
Execute 1,000 concurrent blocking calls using Executors.newVirtualThreadPerTaskExecutor and verify fast completion without OOM.
import java.time.Duration;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class VirtualThreadLab {
public static void main(String[] args) {
var completed = new AtomicInteger();
try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {
for (int i = 0; i < 1_000; i++) {
executor.submit(() -> {
Thread.sleep(Duration.ofMillis(40));
completed.incrementAndGet();
return null;
});
}
} // Auto-closes and waits cleanly until all 1,000 tasks complete
System.out.println("Completed tasks = " + completed.get());
}
}
Completed tasks = 1000
- `try (var executor = Executors.newVirtualThreadPerTaskExecutor())` guarantees structured shutdown and completion waiting.
- While each task executes `Thread.sleep(40ms)`, the JVM unmounts the virtual thread off its carrier OS thread.
- All 1,000 tasks finish concurrently in roughly ~50–100 ms rather than 40+ seconds.
Common Mistakes to Avoid
- Holding a `synchronized` lock across slow HTTP or JDBC I/O calls inside Java 21, pinning the virtual thread to its carrier OS thread.
- Expecting Virtual Threads to speed up CPU-bound prime/video crunching loops (CPU parallelism still depends strictly on core count).
Production Best Practices
- Replace `synchronized` guards around network/DB calls with `ReentrantLock` in Java 21 libraries.
- Control downstream database saturation using a bounded `Semaphore` + HikariCP pool instead of artificially sizing thread pools.
Technical Interview Relevance
High-signal SDE-1/SDE-2 Java 21 interview topic distinguishing green/virtual threads from `CompletableFuture` reactive pipelines.
Practice & Self-Check Questions
Why should you guard a database pool with a `Semaphore` instead of a fixed Virtual Thread pool?
Virtual threads are cheap task wrappers (one per request); limiting concurrency per external resource via a Semaphore preserves the per-task thread model without starving unrelated work.