CompletableFuture: common mistakes and practice
A review of this module. Skip it if you feel confident; the next module does not need it.
Fix the mistakes
The slips that cost marks in this module. Spot each one, then check the fix.
Most CompletableFuture bugs come from three habits: waiting too early, never looking at the error, and using thenApply for a method that already returns a future. Each one has a short, reliable fix.
Mistake 1: calling join() too early
Joining too early means calling join() right after starting a task, before the other tasks have even started. The code looks async, but each task waits for the one before it, so nothing overlaps.
Example 1 · Mistake: join right after each start
import java.util.List;import java.util.concurrent.CompletableFuture;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.atomic.AtomicInteger;
public class JoinTooEarlyDemo { static AtomicInteger running = new AtomicInteger(); static AtomicInteger maxRunning = new AtomicInteger();
static int call(int value) { int now = running.incrementAndGet(); maxRunning.accumulateAndGet(now, Math::max); // remember the highest overlap try { Thread.sleep(100); // pretend network call } catch (InterruptedException e) { Thread.currentThread().interrupt(); } running.decrementAndGet(); return value; }
public static void main(String[] args) { ExecutorService io = Executors.newFixedThreadPool(3); try { int a = CompletableFuture.supplyAsync(() -> call(1450), io).join(); int b = CompletableFuture.supplyAsync(() -> call(600), io).join(); int c = CompletableFuture.supplyAsync(() -> call(45), io).join(); System.out.println("Too early: Rs " + (a + b + c) + ", at most " + maxRunning.get() + " call running");
maxRunning.set(0); List<CompletableFuture<Integer>> calls = List.of( CompletableFuture.supplyAsync(() -> call(1450), io), CompletableFuture.supplyAsync(() -> call(600), io), CompletableFuture.supplyAsync(() -> call(45), io)); int total = calls.stream().mapToInt(CompletableFuture::join).sum(); System.out.println("Start all, then join: Rs " + total + ", at most " + maxRunning.get() + " calls running"); } finally { io.shutdown(); } }}Too early: Rs 2095, at most 1 call running Start all, then join: Rs 2095, at most 3 calls running
What this code does
- Both halves give the same total, so the bug is easy to miss. The counter shows the difference: with
join()after each start, only one call ever runs at a time, taking about 300 ms in total. - Starting all three first lets them overlap on the three pool threads, so the work takes about 100 ms. The
join()calls in the stream come after every task has started.
The fix is a simple order: start every independent task first, keep the futures, and only then wait, with thenCombine, allOf or one join() per future. Keep join() for the edge of the program, such as the end of main or a test.
Mistake 2: lost exceptions at the end of a chain
A lost exception is an error stored inside a future that nobody ever reads. Unlike a plain thread, a failing CompletableFuture task prints no stack trace: the error waits quietly in the future until someone calls join(), get() or a handler.
Example 2 · Mistake: the SMS failed and nobody noticed
import java.util.concurrent.CompletableFuture;import java.util.concurrent.CompletionException;
public class LostErrorDemo { static void sendSms(String order) { throw new IllegalStateException("SMS gateway down"); }
static Throwable unwrap(Throwable ex) { if (ex instanceof CompletionException && ex.getCause() != null) { return ex.getCause(); } return ex; }
public static void main(String[] args) throws InterruptedException { CompletableFuture<Void> sms = CompletableFuture.runAsync(() -> sendSms("ORD-17")); Thread.sleep(100); // the task has long finished by now System.out.println("ORD-17: customer notified"); // wrong, and no error printed System.out.println(" (error hidden in the future: " + sms.isCompletedExceptionally() + ")");
boolean sent = CompletableFuture.runAsync(() -> sendSms("ORD-18")) .whenComplete((v, ex) -> { if (ex != null) { System.out.println("[alert] ORD-18 SMS failed: " + unwrap(ex).getMessage()); } }) .handle((v, ex) -> ex == null) .join(); System.out.println("ORD-18: customer notified? " + sent); }}ORD-17: customer notified (error hidden in the future: true) [alert] ORD-18 SMS failed: SMS gateway down ORD-18: customer notified? false
What this code does
- For ORD-17 the task threw, but no stack trace appeared and the program printed a false success. The error is only visible if someone asks the future.
- For ORD-18 the chain ends with
whenCompleteto raise an alert andhandleto turn the outcome into aboolean, andjoin()makes sure the ending runs.
Fire-and-forget calls such as runAsync(() -> sendSms()) are the usual victims. The SMS fails, nothing is printed, and the app happily reports success. Every chain needs an ending that looks at the outcome: a whenComplete or exceptionally that logs the error, and a join() or a stored future that someone checks.
Mistake 3: thenApply where thenCompose is needed
thenApply with an async method produces a nested CompletableFuture<CompletableFuture<T>>. Usually the next line does not compile; sometimes, with var or Object, it compiles and prints a future instead of the data.
Example 3 · Mistake: a future where the orders should be
import java.util.List;import java.util.concurrent.CompletableFuture;
public class NestedByMistakeDemo { static CompletableFuture<String> findUser(int id) { return CompletableFuture.supplyAsync(() -> "Riya"); }
static CompletableFuture<List<String>> fetchOrders(String user) { return CompletableFuture.supplyAsync(() -> List.of("Keyboard", "Mouse")); }
public static void main(String[] args) { var wrong = findUser(7).thenApply(user -> fetchOrders(user)); Object value = wrong.join(); System.out.println("thenApply gave: " + value.getClass().getSimpleName());
var right = findUser(7).thenCompose(user -> fetchOrders(user)); System.out.println("thenCompose gave: " + right.join()); }}thenApply gave: CompletableFuture thenCompose gave: [Keyboard, Mouse]
What this code does
varhides the type, so the wrong version compiles:wrongis aCompletableFuture<CompletableFuture<List<String>>>, and its value is another future, not the orders.- With
thenComposethe future is flat, andjoin()gives the list straight away.
The tempting fix, thenApply(u -> fetchOrders(u).join()), compiles but blocks a pool thread. The real fix is one word: thenCompose.
A full pipeline: compose, combine, recover
A real pipeline mixes everything: dependent calls with thenCompose, independent calls with thenCombine or allOf, a timeout on each outside call, a fallback where a default is acceptable, and an executor that is shut down at the end.
Example 4 · Tatkal booking: compose, combine, time out, recover
import java.util.concurrent.CompletableFuture;import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.TimeUnit;
record Passenger(String name, String train) {}
public class TatkalBookingDemo { static void sleep(long ms) { try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }
static CompletableFuture<Passenger> login(String user, ExecutorService io) { return CompletableFuture.supplyAsync(() -> new Passenger("Riya Sharma", "12951"), io) .orTimeout(500, TimeUnit.MILLISECONDS); }
static CompletableFuture<Integer> fare(String train, ExecutorService io) { return CompletableFuture.supplyAsync(() -> 2290, io) .orTimeout(500, TimeUnit.MILLISECONDS); }
static CompletableFuture<String> insuranceOffer(String train, ExecutorService io) { return CompletableFuture.supplyAsync(() -> { sleep(200); return "Travel insurance Rs 150"; }, io).completeOnTimeout("no insurance offer", 100, TimeUnit.MILLISECONDS); // optional }
public static void main(String[] args) throws InterruptedException { ExecutorService io = Executors.newFixedThreadPool(4); try { String ticket = login("riya_s", io) // dependent .thenCompose(p -> fare(p.train(), io) .thenCombine(insuranceOffer(p.train(), io), // independent (rupees, insurance) -> p.name() + ", train " + p.train() + ", Rs " + rupees + ", " + insurance)) .exceptionally(ex -> "Booking failed, please retry") .join(); System.out.println(ticket); } finally { io.shutdown(); io.awaitTermination(1, TimeUnit.SECONDS); } System.out.println("Pool terminated: " + io.isTerminated()); }}Riya Sharma, train 12951, Rs 2290, no insurance offer Pool terminated: true
What this code does
- Login comes first because fare and insurance offer need the train number (
thenCompose). Fare and insurance offer do not need each other, so they run side by side (thenCombine). - Required calls get
orTimeoutand fall through to the one finalexceptionally; the optional insurance offer gets its owncompleteOnTimeoutdefault. The pool is shut down and awaited infinally. The insurance site takes 200 ms, longer than its 100 ms limit, so the default offer is used.
Write it in that order and read it by its types. When a step is required, let its failure reach one final exceptionally; when it is optional, give it its own fallback straight away.
Finish up
Mark complete & continue
Next: What is a deadlock?