๐คต 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.
- In this restaurant, each 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. Most of them are just standing there, waiting on the kitchen.
- The next table can't be served. There's no free waiter, even though nobody is actually doing anything.
- Now every table has an order slip, which costs almost nothing. A few waiters carry slips around.
- While table 1's food cooks, the waiter pins the slip to the kitchen pass and goes to serve other tables.
- When the food is ready, any free waiter picks up the slip and carries on where it left off.
- Virtual threads help when tables mostly wait. If an order needs the waiter to actually work hard, there are still only a few waiters.
- 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.
- 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.