A waiter per table
In this restaurant every table gets its own waiter, who stands beside it the whole time the food is cooking. Waiters are expensive, so there are only so many. On a busy night, most waiters are standing still, and new guests can't be served.
The thread-per-request limit
Classic Java servers give each request a platform thread, which is an OS thread: about a megabyte of stack, and costly to create and switch. Pools are capped at a few hundred. Most of those threads spend their time blocked on I/O, waiting for a database or another service, so throughput hits the thread limit long before the CPU is busy.
Reactive and CompletableFuture code works around this, at the cost of harder-to-read code and stack traces.
Pin it to the pass
Now every table's order is just a slip, which costs almost nothing. A few waiters carry slips around. When food is cooking, the waiter pins the slip to the kitchen pass and serves someone else. When it's ready, any free waiter picks it up.
Mounting and unmounting
A virtual thread is a Thread managed by the JVM. It runs on a small pool of carrier threads (about one per core).
When it blocks on I/O, the JVM unmounts it, saving its stack on the heap, and the carrier runs another. When the I/O
finishes, it's remounted on any carrier.
1try (var executor = Executors.newVirtualThreadPerTaskExecutor()) {2for (var order : orders) executor.submit(() -> ship(order)); // plain blocking code3}
In Spring Boot 3.2+, spring.threads.virtual.enabled=true runs request handling on virtual threads.
Where it doesn't help
More slips don't make the cooking faster: if the work is the waiter's own effort, there are still only a few waiters. And if the kitchen only handles ten orders at a time, limit that with a ticket system, not by hiring fewer waiters.
Caveats
- Virtual threads speed up waiting, not computing. CPU-bound work is still limited by cores.
- Pinning: native calls (and, before JDK 24, blocking inside
synchronized) keep the carrier busy. - Don't pool them; create one per task. Limit scarce resources with a
Semaphoreor connection pool. - Be careful with large
ThreadLocalcaches, since there may be millions of threads.