Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 12 / Topic 4 of 7

CompletableFuture: composing async results

A plain Future can only be waited on with get() — there's no way to say "and then do this with the result" without blocking the calling thread. CompletableFuture<V> adds that: a chain of callbacks that run as soon as a value becomes available, without ever blocking a thread just to wait. Think of a courier tracking page that emails you the moment your parcel is out for delivery, instead of you refreshing the page every five minutes to check.

Method Does
supplyAsync(fn, pool) runs fn on the pool, returns a future for its result
thenApply(fn) transforms the result once it arrives (sync, cheap work)
thenCompose(fn) chains to another async call that needs this result (avoids a "future of a future")
thenCombine(other, fn) combines two independent futures once both finish
exceptionally(fn) supplies a fallback value if the chain failed
orTimeout(n, unit) fails the future if it isn't done in time
completeOnTimeout(value, n, unit) supplies a fallback value instead of failing, if it isn't done in time
String report = lookupPincode("ORD-1", pool)
        .thenCompose(pincode -> fetchEta(pincode, pool)
                .thenApply(days -> "ORD-1 ships to " + pincode + ", arrives in " + days + " days"))
        .join();
$ javac CompletableFutures.java
$ java CompletableFutures
== thenCompose: the second call needs the first result ==
ORD-1 ships to 411001, arrives in 2 days

== thenCombine: two independent calls, run in parallel ==
eta 2 days, fee Rs. 40.0
ran in parallel, under 280 ms: true

== exceptionally: recover instead of crashing ==
fallback: no such order: ORD-9

== orTimeout: give up on a call that is taking too long ==
timed out: TimeoutException

== completeOnTimeout: fall back to a cached value instead ==
cached: 3 days (stale)

thenCombine runs fetchEta and fetchDeliveryFee on the pool at the same time (each one sleeps 150 ms); the combined result lands in under 280 ms, not 300+, proving they overlapped rather than ran one after the other. thenCompose is the right call specifically because fetchEta needs the pincode lookupPincode hasn't produced yet — thenApply would have left you with an unusable CompletableFuture<CompletableFuture<Integer>>. exceptionally and completeOnTimeout both turn a failure into a usable value instead of propagating an exception out of join(); orTimeout is for when a failure really should propagate.

🔍 Going deeper: join() is get() without the checked InterruptedException/ExecutionException — it throws an unchecked CompletionException instead, which is why these examples use join() freely inside a try/finally without a throws clause.

Full program: examples/CompletableFutures.java.

Done here? The practice set for Part 12 — including the solutions — is on the part page.

Search the guide