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 CompletableFuture and async

๐Ÿ“Ÿ CompletableFuture and async: cheat sheet

๐ŸŽจ The analogyOrdering at a cafรฉ and getting a buzzer: order everything at once, sit down, and collect when it buzzes.
๐ŸŽ“ The regular explanationStarting work without waiting for it. A CompletableFuture is a result that will arrive later, which you can combine, chain and recover from, so independent calls run in parallel instead of one after another.
Waiting at the tillStep 2 of 2
๐Ÿง’You600 msโ˜•Coffee bar๐ŸฅBakery counter
  1. You order a coffee and stand at the till until it's ready. You can't do anything else.
  2. Only then do you go and order a pastry, and wait again.
Getting a buzzerStep 3 of 3
๐Ÿง’You300 ms๐Ÿง‘โ€๐ŸณCafรฉ staffโ˜•Coffee bar๐ŸฅBakery counter
  1. You order both at once and get two buzzers. You're free to go and sit down.
  2. The coffee and the pastry are made at the same time, by different people.
  3. When both buzzers have gone off, you pick up your tray. 300 ms of waiting instead of 600.
Then, then, unless it goes wrongStep 3 of 3
๐Ÿง’Youmax 2 s๐Ÿ›Ž๏ธFront deskโœ• โœ•๐Ÿ’ซKitchen๐ŸชPlan B snack
  1. You give one set of instructions. Find my table, then bring my usual order to it.
  2. The kitchen is closed. The instructions included "if anything goes wrong, bring a cookie", so you get a cookie.
  3. And because you set a timer, you'd never wait more than two seconds anyway.

๐Ÿงฉ Key questions

What's the problem with standing at the till for each order?
You wait for things that didn't need to wait for each other. The pastry didn't need the coffee at all, but you waited for both, one by one.
You order both things at once and get buzzers. When do you pick up your tray?
When both buzzers have gone off. The staff make both at the same time, and you collect them together.
Your plan says: "if anything goes wrong, bring a cookie instead". What part of the chain is that?
The backup step for when something goes wrong. A plan can include what to do on failure, so nobody stands around deciding.