A shopping app asks three shops for a price. A bank app fetches a user and then their balance. Doing these calls one after another wastes time, and waiting on each Future.get() wastes threads. With CompletableFuture you describe the whole flow up front. Each step runs as soon as its input is ready. You can combine results, recover from errors and add time limits, and you only wait at the very end.
In this lesson you will learn
- Starting async work with
supplyAsync - Chaining steps with
thenApply - Combining results with
thenCombine,allOfandanyOf - Handling errors with
exceptionallyandhandle - Adding timeouts with
orTimeout
You should know ExecutorService and Future and functional interfaces.
Chaining and Combining
import java.util.concurrent.*;
public class Main {
static void pause(int ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
// Pretend remote services, each taking 300 ms
static class Api {
static String fetchUser(int id) { pause(300); return "user" + id; }
static int fetchBalance(String user) { pause(300); return user.length() * 1000; }
static double fetchRate() { pause(300); return 1.05; }
}
public static void main(String[] args) {
long t0 = System.nanoTime();
// Run a chain of steps without blocking the main thread
CompletableFuture<Integer> balance =
CompletableFuture.supplyAsync(() -> Api.fetchUser(7)) // step 1 in the background
.thenApply(String::toUpperCase) // transform the result
.thenApply(Api::fetchBalance); // step 2 uses step 1's result
CompletableFuture<Double> rate = CompletableFuture.supplyAsync(Api::fetchRate); // runs at the same time
// Combine two independent results
CompletableFuture<String> report = balance.thenCombine(rate,
(b, r) -> String.format("balance %d, with interest %.2f", b, b * r));
System.out.println("Main thread is free while work happens...");
System.out.println(report.join()); // wait only at the very end
long ms = (System.nanoTime() - t0) / 1_000_000;
System.out.println("Faster than doing all three calls one after another (900 ms)? " + (ms < 850));
}
}
Output
Main thread is free while work happens...
balance 5000, with interest 5250.00
Faster than doing all three calls one after another (900 ms)? true
supplyAsyncruns the code on a background thread and returns aCompletableFutureat once.thenApply(fn)adds a step that runs when the previous one finishes, using its result: fetch user, upper-case it, then fetch the balance.- The exchange rate is fetched at the same time, in a separate future.
thenCombinewaits for both futures and merges their results. The main thread is free the whole time.join()waits for the final result. It is likeget(), but its errors are unchecked, so you need nothrows.- Because the rate request overlaps with the user and balance requests, the total time is about 600 ms rather than 900 ms.
Many Tasks, Errors and Timeouts
import java.util.*;
import java.util.concurrent.*;
public class Main {
static int price(String shop) {
try { Thread.sleep(100L * shop.length()); } catch (InterruptedException e) { }
if (shop.equals("Broken")) throw new IllegalStateException("shop offline");
return shop.length() * 37 % 100 + 400;
}
public static void main(String[] args) {
List<String> shops = List.of("Daraz", "Chaldal", "Broken", "Rokomari");
// Start all requests at once; turn failures into a fallback value
List<CompletableFuture<String>> futures = shops.stream()
.map(s -> CompletableFuture.supplyAsync(() -> price(s))
.thenApply(p -> s + ": " + p + " taka")
.exceptionally(ex -> s + ": unavailable (" + ex.getCause().getMessage() + ")"))
.toList();
// allOf waits for every future
CompletableFuture.allOf(futures.toArray(new CompletableFuture[0])).join();
futures.forEach(f -> System.out.println(f.join()));
// anyOf completes with the first one to finish
Object first = CompletableFuture.anyOf(
CompletableFuture.supplyAsync(() -> { price("Rokomari"); return "slow shop"; }),
CompletableFuture.supplyAsync(() -> { price("Daraz"); return "fast shop"; })).join();
System.out.println("First answer came from: " + first);
// handle: see the result or the error in one place
String msg = CompletableFuture.supplyAsync(() -> price("Broken"))
.handle((value, ex) -> ex == null ? "got " + value : "recovered from " + ex.getCause().getMessage())
.join();
System.out.println(msg);
// orTimeout: give up if it takes too long
try {
CompletableFuture.supplyAsync(() -> price("Very slow shop name"))
.orTimeout(200, TimeUnit.MILLISECONDS).join();
} catch (CompletionException e) {
System.out.println("Timed out: " + e.getCause().getClass().getSimpleName());
}
}
}
Output
Daraz: 485 taka
Chaldal: 459 taka
Broken: unavailable (shop offline)
Rokomari: 496 taka
First answer came from: fast shop
recovered from shop offline
Timed out: TimeoutException
- All four price requests start together.
allOfreturns a future that completes when every one has finished. exceptionallyturns a failure into a normal value. One broken shop does not ruin the page. The real error is wrapped, so read it fromex.getCause().anyOfcompletes with whichever future finishes first: the shop with the shorter delay.handle((value, ex) -> …)receives either the result or the error, and can turn both into one answer.orTimeoutfails the future with aTimeoutExceptionif it takes too long.
| Method | Use |
|---|---|
thenApply | Transform a result (like map) |
thenCompose | Next step itself returns a CompletableFuture (like flatMap) |
thenAccept | Use the result, return nothing |
thenCombine | Merge two independent results |
exceptionally / handle | Recover from errors |
Common Mistakes
- Calling
join()after every step, which removes all the benefit. - Using
thenApplywhen the function returns a future, giving a nestedCompletableFuture<CompletableFuture<T>>; usethenCompose. - Forgetting error handling. An unhandled exception only appears when someone calls
join. - Running slow file or network work on the shared pool, which is small. Pass your own executor as a second argument.
Practice Exercises
Exercise 1. Start two async tasks that return 20 and 22, and print their sum without calling join on each one separately.
Show answer
CompletableFuture<Integer> a = CompletableFuture.supplyAsync(() -> 20);
CompletableFuture<Integer> b = CompletableFuture.supplyAsync(() -> 22);
System.out.println(a.thenCombine(b, Integer::sum).join()); // 42
Exercise 2. What does CompletableFuture.supplyAsync(() -> 10 / 0).exceptionally(ex -> -1).join() return?
Show answer
−1. The division throws ArithmeticException, and exceptionally replaces the failure with −1.
Frequently Asked Questions
What is the difference between thenApply and thenApplyAsync?
thenApply may run the step on the thread that completed the previous stage. thenApplyAsync always hands the step to an executor. Use the async version when the step itself is slow.
Do virtual threads make CompletableFuture unnecessary?
Not entirely. With virtual threads, simple blocking code is often clear enough. CompletableFuture is still useful for combining many results, racing tasks with anyOf, and adding timeouts and fallbacks in a declarative way.
Summary
supplyAsyncstarts work in the background and returns a CompletableFuture.- Chain with
thenApply/thenCompose; merge withthenCombine,allOf,anyOf. - Recover with
exceptionallyorhandle; limit waiting withorTimeout. - Call
joinonce, at the end.
Next: Java Bit Manipulation.
