Tech Interview RoomStudy guides

Advanced Java

How do you compose asynchronous work with CompletableFuture, including errors and timeouts?

Advanced · 2 min read · Lesson 5 of 10 in Advanced Java

Composition

  • thenApply(fn): transform the result (like map).
  • thenCompose(fn): chain another async call that returns a CompletableFuture (like flatMap), avoiding nested futures.
  • thenCombine(other, fn): combine two independent futures.
  • allOf(...): wait for all; anyOf(...): first to complete.
  • thenAccept / thenRun: side effects.

Threads

Non-Async variants run on whichever thread completes the previous stage (or the caller if already done). *Async variants without an executor use ForkJoinPool.commonPool(). For blocking I/O, always pass a dedicated executor (or a virtual-thread executor).

Errors

  • exceptionally(fn): recover from a failure.
  • handle((result, ex) -> ...): always runs, sees both.
  • whenComplete: side effect, does not change the result.
  • Exceptions arrive wrapped in CompletionException; unwrap getCause().

Timeouts (Java 9+)

orTimeout(d, unit) completes exceptionally with TimeoutException; completeOnTimeout(value, d, unit) completes with a fallback. Note that the underlying task keeps running unless you cancel it at the source.

Example

java
ExecutorService io = Executors.newVirtualThreadPerTaskExecutor();

CompletableFuture<Profile> profile = supplyAsync(() -> users.get(id), io);
CompletableFuture<List<Order>> orders = supplyAsync(() -> orderClient.recent(id), io)
        .completeOnTimeout(List.of(), 300, MILLISECONDS);          // degrade gracefully
CompletableFuture<Score> score = profile.thenCompose(p -> supplyAsync(() -> risk.score(p), io));

Dashboard d = profile.thenCombine(orders, Dashboard::new)
        .thenCombine(score, Dashboard::withScore)
        .exceptionally(ex -> Dashboard.unavailable(ex.getCause()))
        .join();

The profile, orders and score calls run concurrently, so latency is the slowest branch rather than the sum.

Follow-up questions interviewers ask

Try answering each one before you open it.

What is the difference between thenApply and thenCompose?

thenApply with a function returning CompletableFuture<T> gives you CompletableFuture<CompletableFuture<T>>. thenCompose flattens it into CompletableFuture<T>, chaining the second async call after the first. Use thenCompose when the next step is itself asynchronous.

join() vs get()?

Both block. get() throws checked InterruptedException and ExecutionException, and has a timeout overload. join() throws unchecked CompletionException, which is more convenient inside lambdas and streams. In request-handling code, prefer composing to the end and blocking once (or returning the future to a framework that supports it, such as Spring MVC's CompletableFuture return type).

How do errors behave with allOf?

allOf completes exceptionally if any input fails, but only after all inputs complete, and its result is Void. To collect partial results, attach exceptionally or handle to each future first, then allOf and read each with join(). To fail fast, complete a shared future exceptionally as soon as any one fails.