TwiceToldby Develoker
ConceptsSystem designLabsCheat sheetsAbout

Develoker makes free tools for learning to build software. TwiceTold explains each idea twice, as an everyday analogy and the real thing; CloudArch lets you design cloud systems and put load on them.

About ยท Labs ยท Cheat sheets ยท Learning paths

โ† Back to Virtual threads

๐Ÿคต Virtual threads: cheat sheet

๐ŸŽจ The analogyA few waiters serving hundreds of tables, pinning each order to the pass instead of waiting beside one table.
๐ŸŽ“ The regular explanationLightweight threads managed by the JVM (Java 21+). When one blocks on I/O, it's parked and its carrier OS thread serves others, so simple blocking code can handle huge numbers of concurrent requests.
One waiter per tableStep 3 of 3
๐Ÿช‘Table 1๐Ÿช‘Table 2๐Ÿช‘Table 3๐ŸคตWaiters200 of 200 waiting๐ŸณKitchen
  1. In this restaurant, each table gets its own waiter, who stands beside it the whole time the food is cooking.
  2. Waiters are expensive, so there are only so many. Most of them are just standing there, waiting on the kitchen.
  3. The next table can't be served. There's no free waiter, even though nobody is actually doing anything.
Waiters who don't stand aroundStep 3 of 3
๐Ÿ“Table 1's orderrunning๐Ÿ“Table 2's orderparked๐Ÿ“Table 3's order๐ŸคตA few waiters๐ŸณKitchen
  1. Now every table has an order slip, which costs almost nothing. A few waiters carry slips around.
  2. While table 1's food cooks, the waiter pins the slip to the kitchen pass and goes to serve other tables.
  3. When the food is ready, any free waiter picks up the slip and carries on where it left off.
When a waiter gets stuckStep 3 of 3
๐Ÿ“An order๐ŸคตWaiter๐ŸณKitchenmax 10
  1. Virtual threads help when tables mostly wait. If an order needs the waiter to actually work hard, there are still only a few waiters.
  2. Some old habits make a waiter stand still with the slip in hand, like waiting in native code, where the slip can't be pinned up.
  3. And don't keep a small team of waiters just for one kitchen. If the kitchen only takes ten orders at a time, limit that with a ticket system instead.

๐Ÿงฉ Key questions

On a busy night, why can't new guests be served?
Most waiters are standing still beside tables waiting for food. Waiters are expensive, so there are only so many.
What does a waiter do while the food is cooking?
Pins the slip to the pass and serves someone else. When the food is ready, any free waiter picks the slip up.
The kitchen can only handle ten orders at a time. What should you do?
Use a ticket system for the kitchen. More slips don't make the cooking faster.