The Plain Picture#
Ordering a meal kit: "When the vegetables and the spices both arrive, combine them into a recipe box, then label it. If the spice supplier fails, use the house spice mix. If nothing arrives in 10 minutes, cancel." You describe the plan up front; the steps run as things arrive, without you standing and waiting at each one.
The Real Names#
A
CompletableFuture<T>is aFutureyou can chain: attach what should happen next, without blocking a thread while waiting.Start:
supplyAsync(supplier, executor)(returns a value),runAsync(runnable, executor).Chain:
thenApply(f)(transform the result — likemap),thenCompose(f)(whenfitself returns a future — likeflatMap, Modern Java Ch 5),thenAccept(consumer),thenCombine(other, f)(wait for two),allOf(...)/anyOf(...).Errors:
exceptionally(f)(fallback value),handle((result, ex) -> ...),whenComplete(...).Timeouts (Java 9+):
orTimeout(t, unit),completeOnTimeout(value, t, unit).Finish:
join()(waits; throws uncheckedCompletionException) orget()(checked exceptions).
Under the Hood#
Two 300 ms calls in parallel, then combined:
CompletableFuture<String> notes = CompletableFuture.supplyAsync(() -> {
sleep(300);
return "notes";
}, pool);
CompletableFuture<String> history = CompletableFuture.supplyAsync(() -> {
sleep(300);
return "history";
}, pool);
String quiz = notes
.thenCombine(history, (n, h) -> "quiz from " + n + " + " + h)
.thenApply(String::toUpperCase)
.join();
// QUIZ FROM NOTES + HISTORY in 307 ms ← not 600: both calls waited at the same timeFallback on failure:
CompletableFuture.supplyAsync(() -> {
throw new IllegalStateException("AI API down");
}, pool)
.exceptionally(ex -> "fallback quiz (" + ex.getCause().getMessage() + ")")
.join();
// fallback quiz (AI API down)Timeouts:
CompletableFuture.supplyAsync(() -> {
sleep(2000);
return "slow";
}, pool)
.orTimeout(200, TimeUnit.MILLISECONDS)
.join();
// timeout: TimeoutException (wrapped in a CompletionException)Always pass your own executor to the ...Async methods. Without one, they use the shared ForkJoinPool.commonPool() — sized for CPU work (cores − 1
threads) and shared with parallel streams (Modern Java Ch 7). Blocking I/O in it starves everything else in the application.
Every call to an external service needs a timeout. A hung AI API without one ties up a thread forever; enough of them and the server stops responding. This "fan out, combine, fall back, time out" shape is the heart of backend service code (Microservices and Service Communication (coming soon)).
Check yourself
4 questionsthenApply vs thenCompose?
Show answerHide answer
thenApply transforms the result with a plain function; thenCompose chains a function that itself returns a CompletableFuture (flattening it).
Why did the combined quiz take ~300 ms, not ~600 ms?
Show answerHide answer
Both calls ran concurrently on the pool, and thenCombine waited for both.
Why pass a custom executor to supplyAsync?
Show answerHide answer
The default common pool is small and shared (including by parallel streams); blocking tasks there starve other work.
How do you give a slow call a deadline?
Show answerHide answer
orTimeout(t, unit) (fail) or completeOnTimeout(fallback, t, unit) (default value).