Card 05/ 08

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.

The two kinds of thread, on cost, scheduling and how many you can have
Compared onPlatform threadVirtual thread
Backed byOne operating-system threadA heap object, run on a carrier thread
StackReserved up front, around a megabyteGrows and shrinks on the heap
Scheduled byThe operating systemThe virtual machine
Practical numberThousandsMillions
While blocked on input or outputIts operating-system thread is idleIt releases its carrier for someone else
java
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.