Card 05/ 08
All 8 cards
ComparisonDifficulty: Advanced1 min
A Platform Thread Against a Virtual Thread
A server holding ten thousand open connections. One thread per connection was the obvious design and was impossible for twenty years, because each thread reserved about a megabyte of stack and asked the operating system for a scheduling slot.
Java 21 finalised virtual threads: threads the virtual machine schedules itself, on a small pool of ordinary threads underneath.
| Compared on | Platform thread | Virtual thread |
|---|---|---|
| Backed by | One operating-system thread | A heap object, run on a carrier thread |
| Stack | Reserved up front, around a megabyte | Grows and shrinks on the heap |
| Scheduled by | The operating system | The virtual machine |
| Practical number | Thousands | Millions |
| While blocked on input or output | Its operating-system thread is idle | It releases its carrier for someone else |
Thread.ofVirtual().start(() -> handle(connection));
try (var pool = Executors.newVirtualThreadPerTaskExecutor()) {
connections.forEach(c -> pool.submit(() -> handle(c)));
}The decision rule. Use virtual threads for work that spends its time waiting — network calls, database queries, file reads. Use platform threads for work that spends its time computing, where there is nothing to release the carrier for and a pool sized to the processor count is the right shape.