Async programming
On this page 8 topics
Overview
Topics
- CompletableFuture
- composition
- exception propagation
- cancellation
Learn first
3 h of practice (estimate)
Learning outcomes
- Compose asynchronous work with
CompletableFuture(thenApply,thenCompose,thenCombine,allOf). - Propagate and handle exceptions in async chains.
- Apply timeouts and cancellation.
- Choose the executor for async stages deliberately.
Lessons
Lab and exercises
Lab
MID-006-LAB1 · Product page aggregator
Outcomes: 1–4 · Time: ~3 h Fetch product, stock, and reviews concurrently from simulated services on a dedicated executor. Apply an overall deadline and per-call timeouts. On failure return partial results with a degraded marker. Acceptance: total latency about equal to the slowest call; failures degrade gracefully.
Exercises (assessment: fix a broken async chain)
| ID | Outcome | Task |
|---|---|---|
| MID-006-EX01 | 1 | Combine two independent price lookups with thenCombine, then fetch the seller using the result with thenCompose. |
| MID-006-EX02 | 1 | Wait for ten futures with allOf and collect the results into a list. |
| MID-006-EX03 | 2 | Given a chain that swallows an exception, fix it so the error is handled and logged with a fallback. |
| MID-006-EX04 | 3 | Add a 200 ms default-on-timeout to a slow call and show the default arriving. |
| MID-006-EX05 | 4 | Fix a chain that runs blocking HTTP calls on the common pool by passing an executor. |
| MID-006-EX06 | 2 | Explain CompletionException vs ExecutionException and unwrap the real cause. |
Show solutions
- EX01
a.thenCombine(b, Math::min).thenCompose(p -> sellerFor(p)). - EX02
CompletableFuture.allOf(arr).thenApply(v -> futures.stream().map(CompletableFuture::join).toList());joinis safe here because all are complete. - EX03 Replace an empty
catchor an unread future with.handle((v, ex) -> { if (ex != null) { log.warn(...); return fallback; } return v; }). - EX04
slow.completeOnTimeout(DEFAULT, 200, MILLISECONDS). - EX05
CompletableFuture.supplyAsync(() -> http.call(), ioPool). - EX06
join()throwsCompletionExceptionandget()throwsExecutionException; both wrap the original ingetCause().
Quiz
Outcomes: O1 composing stages · O2 errors · O3 timeouts and cancellation · O4 executors.
A self-check for you: nothing is graded, saved or sent anywhere. Choose an answer, then check it. You can try again as often as you like.
Practical part
Six exercises MID-006-EX01 to EX06 including fixing a broken async chain, plus the lab. Pass: at least five exercises correct and the lab showing latency near the slowest call with graceful degradation.
Common mistakes
Blocking join() inside stages; losing exceptions; using the common pool for blocking I/O.
Assessment
Fix a broken async chain.
Career relevance
Resilience patterns (MID-033).