โ 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.
- You order a coffee and stand at the till until it's ready. You can't do anything else.
- Only then do you go and order a pastry, and wait again.
- You order both at once and get two buzzers. You're free to go and sit down.
- The coffee and the pastry are made at the same time, by different people.
- When both buzzers have gone off, you pick up your tray. 300 ms of waiting instead of 600.
- You give one set of instructions. Find my table, then bring my usual order to it.
- The kitchen is closed. The instructions included "if anything goes wrong, bring a cookie", so you get a cookie.
- 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.