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

All concepts · java · concurrency · async

CompletableFuture and async

Starting 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.

10 min3 animations

📚 Builds on🖊️ Threads, locks and race conditions

🖨️ Cheat sheet

Waiting at the till

You order a coffee and stand at the till until it's made. Then you order a pastry and wait again. You spent all that time standing still, and the pastry didn't need the coffee at all.

Blocking calls add up

A typical request handler calls several services one after another. Each blocking call holds the thread while it waits on the network, so independent calls of 300 ms each add up: two take 600 ms, three take 900 ms.

Waiting at the till2 steps
🧒You☕Coffee bar🥐Bakery counter
Press play and watch it happen!

A buzzer

A better café gives you a buzzer. You order both things at once, sit down, and the staff make them at the same time. When both buzzers go off, you pick up your tray.

Futures that combine

A CompletableFuture<T> is a value that will be available later. Start work with supplyAsync, then say what to do with the results:

1var price = CompletableFuture.supplyAsync(() -> prices.get(id), executor);2var stock = CompletableFuture.supplyAsync(() -> stockLevels.get(id), executor);3 4CompletableFuture<Offer> offer = price.thenCombine(stock, Offer::new);

Both calls run in parallel, so the total time is the slowest one. allOf waits for many. Pass your own executor rather than relying on the common pool for I/O work.

Getting a buzzer3 steps
🧒You🧑‍🍳Café staff☕Coffee bar🥐Bakery counter
Press play and watch it happen!

A chain of instructions

You can hand over a whole plan: "find my table, then bring my usual order, and if anything goes wrong, bring a cookie instead." Nobody has to stand and wait between steps.

Chaining and errors

MethodUse
thenApplyTransform the result
thenComposeStart another async step that needs the result
thenCombine / allOfWait for several
exceptionally / handleRecover from failure
orTimeoutFail if it takes too long

An exception inside a stage completes the future exceptionally and skips the following stages until a handler. Calling join() or get() blocks, so do it only at the edge. With virtual threads, simple blocking code is often a clearer alternative.

Then, then, unless it goes wrong3 steps
🧒You🛎️Front desk🍳Kitchen🍪Plan B snack
Press play and watch it happen!

🔎 Spot it in real code

This is the café with buzzers as real Java code. A customer orders a coffee and a pastry at once, sits down, and collects one tray. Pick a label, then tap the line where that happens.

Tap the line where you see: Placing the orders and getting buzzers.

0 of 5 placed

🧩 Finish the code

Now write the café order yourself. Look up a customer, then, once that is ready, order their usual. The customer must never stand at the till, and slow lookups go to the café's own staff, not a small team every shop on the street shares. An order that takes more than two seconds counts as a failed order, and any failed order ends with an empty tray. Pick the right piece of code for each numbered gap.
  1. 1 Use the café's own team of staff for waiting jobs
  2. 2 Once the customer is found, place a new order that gets its own buzzer
  3. 3 Treat an order that takes over two seconds as a failure
  4. 4 If anything went wrong, hand over an empty tray
1// Load a user's orders without ever blocking a request thread2CompletableFuture<List<Order>> result = CompletableFuture3        .supplyAsync(() -> users.find(id), 1)4        .2(user -> CompletableFuture.supplyAsync(() -> orders.of(user), ioPool))5        .36        .4(ex -> List.of());
0 of 4 gaps filled

🧩 Quick quiz

Quick quiz! 3 questions about CompletableFuture and async, told the same way as the story.
  1. What's the problem with standing at the till for each order?
  2. You order both things at once and get buzzers. When do you pick up your tray?
  3. Your plan says: "if anything goes wrong, bring a cookie instead". What part of the chain is that?
Answer every question to check.Passing marks CompletableFuture and async as done.
Got the hang of CompletableFuture and async? Mark it as done, and your paths show how far you’ve got.

Saved in this browser.

☕ Java concurrencyStep 3 of 5

← Previous on the path🗒️ The Java memory model and volatileNext on the path →🤵 Virtual threads