SteelReed

Search

Search posts, questions…

3. Advanced Java

CompletableFuture and asynchronous programming in Java

Calling three services in parallel the right way: choosing the executor (the common ForkJoinPool trap), thenApply/thenCompose/thenCombine/allOf/anyOf, unwrapping CompletionException, timeouts and the limits of cancel, carrying MDC/SecurityContext, Spring @Async proxy traps, when virtual threads are simpler, structured concurrency from preview to final in JDK 28; how to review async code written by AI.

18 Nov 20268 min readSenior

–

1. The problem

A dashboard API calls profile (300 ms), orders (500 ms) and points (200 ms) one after another: the user waits 1,013 ms. Switching to supplyAsync without an executor gets 506 ms on a laptop, but under load the whole JVM chokes on the common pool. Adding orTimeout makes the log say "timeout" while the thread still hangs on the socket.

2. Key idea

Parallel calls turn "total time" into "the slowest branch", but every branch still holds a thread and a connection. A future is just a claim ticket: tearing it up doesn't make the worker stop. Work only stops when the I/O has a timeout or the task checks a cancellation flag.

Before fanning out, answer four questions: are the branches independent, which threads do they run on, where does the timeout live, which branches may be missing (degrade). Branch timeout < API timeout < caller timeout.

Choice Use when Don't use when
Sequential calls a later branch needs an earlier result, or it's already fast enough branches are independent and latency is a measured problem
CF with a dedicated executor the API is already async (HttpClient.sendAsync), per-step timeouts new Java 21+ code that just needs "call three places and merge"
Virtual threads + blocking code new business code on Java 21+ heavy computation; downstreams without concurrency limits
Structured concurrency one branch failing must really cancel the rest your JDK lacks the final version and you won't accept preview

3. In Java

JAVA
// io: a dedicated executor (bounded pool or virtual threads), not the common pool
List<String> degraded = Collections.synchronizedList(new ArrayList<>());
var p = CompletableFuture.supplyAsync(() -> profileClient.get(id), io);   // required
var o = CompletableFuture.supplyAsync(() -> orderClient.of(id), io)       // client has a read timeout
        .exceptionally(ex -> { degraded.add("orders"); return List.of(); });
var pt = CompletableFuture.supplyAsync(() -> pointsClient.of(id), io)
        .exceptionally(ex -> { degraded.add("points"); return 0; });
return CompletableFuture.allOf(p, o, pt)
        .orTimeout(1, TimeUnit.SECONDS)        // frees the waiter, doesn't stop the tasks
        .thenApply(v -> new Dashboard(p.join(), o.join(), pt.join(), List.copyOf(degraded)))
        .join();                               // errors are wrapped: unwrap(ex) before checking type

Other languages: Go uses errgroup.WithContext, where one failing goroutine cancels ctx for the others; Node.js Promise.all fails fast but doesn't cancel the other promises, so pass an AbortController.

Composing steps, exceptions, context and @Async
  • thenApply: transform the result. thenCompose: the next step returns another CF (avoids CF<CF<T>>). thenCombine: merge two independent CFs. anyOf: take whichever finishes first.
  • Errors in a chain reach you as CompletionException (or ExecutionException with get()); take getCause() before checking instanceof.
  • exceptionally(ex -> null) at the end swallows every error; put the fallback right after the optional branch.
  • MDC and SecurityContext are bound to threads: use a TaskDecorator or Context Propagation to carry them to the executor.
  • @Async works through a proxy: calling this.method() in the same class runs synchronously. Return CompletableFuture<T> rather than void so errors don't vanish.
  • Callbacks without the Async suffix may run on whatever thread completed the previous CF, including an I/O thread.

4. Working with AI

Hand to AI: a fan-out skeleton with tests simulating per-branch latency, an unwrap helper with tests, converting a CF chain to virtual threads and comparing measurements.

Check yourself in AI-written code:

  • Every supplyAsync, runAsync, ...Async has an executor; grepping Async( finds none without it.
  • HTTP/JDBC clients have connect and read timeouts; orTimeout isn't the only protection.
  • No exceptionally(ex -> null) at the end of a chain; errors are unwrapped before type checks.
  • Executors have thread names, bounded queues and a busy-thread metric.
  • Logs in async tasks keep the trace id; @Async isn't called through this.

5. Exercises

Exercise 1: Review a dashboard "with timeouts and degrade"

Requirements: profile is required; orders and points are optional, at most 800 ms each, and on failure or timeout return empty and record their name in degraded. Simulation: orders hangs 2 s, points throws 503. The AI says "the 800 ms timeout protects the pool". Find two bugs, name a test, fix it.

JAVA
var p  = CompletableFuture.supplyAsync(Exercise::profile);
var o  = CompletableFuture.supplyAsync(Exercise::orders)
        .orTimeout(800, TimeUnit.MILLISECONDS)
        .exceptionally(ex -> List.of());
var pt = CompletableFuture.supplyAsync(Exercise::points).exceptionally(ex -> 0);
return CompletableFuture.allOf(p, o, pt)
        .thenApply(v -> new Dashboard(p.join(), o.join(), pt.join(), List.of())).join();
Solution 1
  • No executor: all three branches run on the common pool; orders hanging 2 s holds a common-pool thread, and under load the whole JVM chokes.
  • orTimeout only frees the waiter: the orders thread still hangs for 2 s, so "protects the pool" is false. The 800 ms timeout belongs in the HTTP client's read timeout.
  • Also: degraded is always empty, and profile has no timeout.
  • Test: simulate orders hanging, fire 20 concurrent requests, measure busy executor threads after 1 s; assert degraded contains orders.
  • Fix as in section 3: a dedicated executor, a client with an 800 ms read timeout, fallbacks that record degraded, orTimeout on profile.

Exercise 2: Choose how to "fail fast on one branch"

allOf waits for every branch even after one has failed. You need allOrFail: if one branch fails, report immediately and cancel the rest. The AI offers: (A) hand-written with whenComplete + cancel(true); (B) StructuredTaskScope. The service runs JDK 21. Which one, and what would flip the choice?

Solution 2
  • JDK 21 without preview: pick A, knowing that cancel(true) on a CF doesn't interrupt the task, so slow tasks run to completion. To really free threads, tasks need timeouts at the I/O layer.
  • B really cancels through interrupts, but on JDK 21 it's a preview and the API changed between releases. Pick B once you're on a JDK where structured concurrency is final.
  • If you already use virtual threads and blocking code, B is much simpler: no unwrap, no hand-wired whenComplete.

Summary

  • Parallel: time ≈ the slowest branch, if the branches are truly independent.
  • Always pass an executor; never run I/O on the common pool.
  • orTimeout and cancel don't stop the underlying work: real timeouts live in the client.
  • Fallbacks right after optional branches; unwrap CompletionException.
  • Java 21+: virtual threads with blocking code are often simpler than CF chains.

Further reading: ExecutorService and virtual threads.

Practice interview questions on this topic

All Concurrency questions →

Loading comments…
Next on the roadmapSOLID by problem: five ways to lower the cost of change, and when you don't need them