Introduction
The Java CompletableFuture chaining API shipped in March 2014 as part of Java 8 (JSR-335) by Brian Goetz and the Lambda Libraries expert group. Before Java 8, the java.util.concurrent.Future interface introduced in Java 5 (September 2004, JSR-166 by Doug Lea) was the standard asynchronous-result handle, but it had a famous limitation: you could only call get() to block, and you could not register a callback that ran when the future completed. CompletableFuture fixed this by giving every future a chainable callback API. For a Java learner, Java CompletableFuture chaining is the modern way to compose async work without callback hell. Interviewers ask about thenApply, thenCompose, and thenCombine because they are the cleanest examples of how Java 8 functional interfaces (Function, BiFunction, Supplier) compose with async primitives, and because the three methods are easy to confuse on a whiteboard.
Understanding Java CompletableFuture chaining also clarifies the relationship between the older Future.get, the newer CompletableFuture pipeline, and the reactive Flow API that shipped in Java 9 (September 2017, JEP 266). Every modern Java service-side framework (Spring WebFlux, gRPC-Java, Apache HttpClient 5 async, R2DBC drivers) interoperate with CompletableFuture at its boundaries, so a clean mental model of thenApply, thenCompose, and thenCombine is foundational for writing idiomatic Java service code.
What is Java CompletableFuture Chaining?
Java CompletableFuture chaining is the practice of attaching dependent stages to a CompletableFuture using the thenApply, thenCompose, thenCombine, and related callback methods. A CompletableFuture represents a pending result; chaining attaches functions that transform the result, combine two results, or trigger further async work. Java CompletableFuture chaining belongs to the asynchronous computation category of the java.util.concurrent package. It is different from the older Future in that you do not need to block on get(); instead you compose callbacks that run when the future completes. It is different from the Java 9 Flow API (Publisher, Subscriber, Subscription) in that a CompletableFuture represents exactly one async result, whereas a Flow.Publisher represents a stream of zero or more results.
The three chaining methods differ in what they take and what they return: thenApply takes a Function<T, R> and returns CompletableFuture<R>; thenCompose takes a Function<T, CompletableFuture<R>> and returns CompletableFuture<R> (this is the monadic bind that flattens nested futures); thenCombine takes a second CompletableFuture<U> and a BiFunction<T, U, R> and returns CompletableFuture<R> that completes when both source futures complete. Each method also has an Async variant that runs the function on a different thread (typically ForkJoinPool.commonPool or a custom Executor).
How Java CompletableFuture Chaining Works - Step by Step
Step 1: Creating a CompletableFuture. There are several entry points: CompletableFuture.supplyAsync(Supplier<U>) runs the supplier on ForkJoinPool.commonPool() and completes the future when the supplier returns; CompletableFuture.runAsync(Runnable) is the void-returning variant; new CompletableFuture<U>() returns an uncompleted future you must call complete() on manually. The supplyAsync and runAsync forms also accept a custom Executor as a second argument to run the supplier on a different thread pool.
Step 2: thenApply (synchronous transformation). thenApply takes a Function<T, R> and runs it on whatever thread completes the source future. If the source is already complete when thenApply is called, the function runs synchronously on the caller thread. The result is a new CompletableFuture<R> that completes with the function's return value. This is the closest analogue of java.util.stream.Stream.map for futures.
Step 3: thenCompose (asynchronous transformation). thenCompose takes a Function<T, CompletableFuture<R>> and returns CompletableFuture<R>. This is the crucial difference from thenApply: if your transformation itself returns a future, thenApply would give you CompletableFuture<CompletableFuture<R>>; thenCompose flattens the nesting. This is the monadic bind operation, identical in spirit to Optional.flatMap and Stream.flatMap.
Step 4: thenCombine (combining two futures). thenCombine takes a second CompletableFuture<U> and a BiFunction<T, U, R>. The returned CompletableFuture<R> completes when both source futures complete; if either completes exceptionally, the combined future completes exceptionally with the same cause. The BiFunction runs only after both sources succeed.
Step 5: Async variants. Each of these has an Async suffix: thenApplyAsync, thenComposeAsync, thenCombineAsync. The Async variants run the function on a different thread (typically ForkJoinPool.commonPool or a custom Executor supplied as an extra argument). The non-Async variants run on the completing thread, which is faster but mixes threads.
Step 6: Exception propagation. If any stage in the chain throws, the exception propagates down the chain as a CompletionException wrapping the original cause. You handle it with exceptionally(Function<Throwable, T>), handle(BiFunction<T, Throwable, R>), or whenComplete(BiConsumer<T, Throwable>). exceptionally recovers with a fallback value; handle recovers and inspects both value and error; whenComplete side-effects without recovering (the original value or error propagates unchanged).
Java Program for Java CompletableFuture Chaining
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CompletableFutureChainingDemo {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(4);
try {
// 1. thenApply: transform with a synchronous Function
CompletableFuture<String> f1 = CompletableFuture
.supplyAsync(() -> 21, pool)
.thenApply(n -> n * 2)
.thenApply(n -> "doubled=" + n);
// 2. thenCompose: chain a Function that returns another future
CompletableFuture<String> f2 = CompletableFuture
.supplyAsync(() -> "user-14", pool)
.thenCompose(userId -> fetchEmail(userId))
.thenApply(email -> "email=" + email);
// 3. thenCombine: combine two independent futures with a BiFunction
CompletableFuture<Integer> left = CompletableFuture.supplyAsync(() -> 10, pool);
CompletableFuture<Integer> right = CompletableFuture.supplyAsync(() -> 20, pool);
CompletableFuture<String> f3 = left.thenCombine(
right, (a, b) -> "sum=" + (a + b));
// 4. Pipeline combining all three operators
CompletableFuture<String> pipeline = CompletableFuture
.supplyAsync(() -> 100, pool)
.thenCompose(v -> CompletableFuture.supplyAsync(() -> v + 50, pool))
.thenCombine(CompletableFuture.supplyAsync(() -> 7, pool),
(x, y) -> x * y)
.thenApply(r -> "final=" + r);
System.out.println(f1.get());
System.out.println(f2.get());
System.out.println(f3.get());
System.out.println(pipeline.get());
} finally {
pool.shutdown();
}
}
// Simulate a remote call that itself returns a future.
static CompletableFuture<String> fetchEmail(String userId) {
return CompletableFuture.supplyAsync(
() -> userId + "@example.com");
}
}
Code Explanation - Line by Line
The main method creates a fixed thread pool of four threads and wraps it in a try-finally so the pool is always shut down. The first pipeline demonstrates thenApply twice: supplyAsync returns the constant 21 on the pool, thenApply(n -> n * 2) doubles it to 42, thenApply(n -> "doubled=" + n) converts to the string "doubled=42". The two thenApply calls compose because each thenApply returns a fresh CompletableFuture and the next call attaches to that returned future.
The second pipeline demonstrates thenCompose. supplyAsync returns the string "user-14"; thenCompose takes that userId and calls fetchEmail(userId), which itself returns a CompletableFuture<String>. Without thenCompose, calling thenApply(fetchEmail) would return CompletableFuture<CompletableFuture<String>> (a future of a future). thenCompose flattens the nesting so the final type is CompletableFuture<String>. The final thenApply formats the email as "email=user-14@example.com".
The third pipeline demonstrates thenCombine. Two independent futures, left (10) and right (20), are created with supplyAsync. thenCombine takes both and a BiFunction that adds them and produces "sum=30". The combined future completes only when both source futures complete; if either had completed exceptionally, the combined future would complete exceptionally with the same cause.
The fourth pipeline combines all three. It starts with supplyAsync returning 100; thenCompose chains an inner supplyAsync that adds 50 (so the value becomes 150); thenCombine merges with another supplyAsync returning 7, multiplying to 1050; thenApply formats as "final=1050". This shows the power of Java CompletableFuture chaining: any combination of sync transforms, async binds, and pairwise merges can be composed fluently in a single expression.
The fetchEmail helper simulates a remote call by returning a CompletableFuture that completes with userId + "@example.com". In real code this would be a WebClient call, a JDBC async call, or a Kafka producer future; the shape of the API is the same.
Interview Questions and Answers
Q1. What is the difference between thenApply and thenCompose?
thenApply takes a Function<T, R> and runs it synchronously on the completing thread, returning CompletableFuture<R>. thenCompose takes a Function<T, CompletableFuture<R>> and returns CompletableFuture<R>, flattening the nested future. Use thenApply when your transformation is a pure synchronous function; use thenCompose when your transformation itself returns a future (another async step). Calling thenApply with a function that returns a CompletableFuture gives you CompletableFuture<CompletableFuture<R>>, which is almost never what you want.
Q2. What is the difference between thenApply and thenApplyAsync?
thenApply runs the function on the thread that completes the source future; if the source is already complete, this is the caller thread. thenApplyAsync always runs the function on a different thread, by default ForkJoinPool.commonPool(). The Async variants are useful when the function is expensive (to avoid blocking the IO thread that completed the source), but they add task-submission overhead and thread-context-switch cost that can dominate for cheap functions.
Q3. What does thenCombine do and how does it differ from thenCompose?
thenCombine merges two independent futures with a BiFunction: it waits for both source futures to complete and then applies the function to both results. thenCompose chains a single source future through a transformation that returns another future. The two operate on different shapes of data: thenCompose is sequential (one stage feeds the next), thenCombine is parallel (two stages feed a single combiner). For more than two parallel futures, use CompletableFuture.allOf to wait for all of them, then combine their results manually.
Q4. How does exception propagation work in a CompletableFuture chain?
If a stage throws an exception, the exception is wrapped in a CompletionException and the returned future completes exceptionally. All downstream stages that depend on the failed future also complete exceptionally with the same cause, unless you attach a handler. Use exceptionally(Function<Throwable, T>) to recover with a fallback value, handle(BiFunction<T, Throwable, R>) to recover and inspect both the value and the error, or whenComplete(BiConsumer<T, Throwable>) to side-effect without recovering (the original value or error propagates unchanged).
Q5. What thread runs the function in thenApply if the source future is already complete when the chain is attached?
The JDK specifies that if the source future is already complete when thenApply is called, the function runs synchronously on the caller thread of thenApply. This is a subtle but important detail: it means thenApply on an already-completed future can unexpectedly block the caller thread, which can be a problem if the caller is a Netty IO thread or a UI thread. To guarantee the function runs off-thread regardless of source state, use thenApplyAsync with a custom Executor.
Q6. What is the difference between ForkJoinPool.commonPool() and a custom Executor for CompletableFuture?
ForkJoinPool.commonPool() is the shared pool used by all *Async methods that do not take an explicit Executor. It is sized to Runtime.getRuntime().availableProcessors() - 1 (with a minimum of 1, configured via the system property java.util.concurrent.ForkJoinPool.common.parallelism). For blocking IO work, the common pool can be exhausted easily; for CPU-bound work it is usually fine. For blocking work (database calls, HTTP) you should always pass a custom Executor (typically a fixed pool sized to the expected concurrency) to the *Async methods, so blocking tasks do not starve parallel streams and other CompletableFuture users.
Q7. Your team has a service that calls three remote APIs sequentially with CompletableFuture, then chains a local CPU-heavy computation. How would you tune the execution model to avoid blocking and minimize latency?
First, identify whether the three remote calls are actually sequential or could be parallel. If they are independent, use thenCombine (for two) or CompletableFuture.allOf (for three) to run them in parallel, then combine their results. Second, do not use thenApply for the CPU-heavy step if the source completes on an IO thread from a remote client; use thenApplyAsync with a custom CPU-bound Executor so the heavy work does not block the IO thread. Third, use exceptionally or handle at the boundary of each remote call to convert failures to fallback values, so one remote failure does not bring down the whole pipeline. Fourth, set timeouts with orTimeout so a slow remote does not stall the entire chain indefinitely.
Sample Input and Output
Input: A fixed thread pool of size 4.
f1 source value: 21, transformed by n * 2 then "doubled=" prefix.
f2 source value: "user-14", chained through fetchEmail which appends "@example.com".
f3 two independent sources: left=10, right=20, combined by (a,b) -> "sum=" + (a + b).
pipeline: 100 -> +50 -> *7 -> "final=" prefix.
Output:
doubled=42
email=user-14@example.com
sum=30
final=1050
The output confirms four behaviours: the two thenApply calls composed correctly to produce "doubled=42"; thenCompose flattened the nested future returned by fetchEmail into a single future producing "email=user-14@example.com"; thenCombine merged the two independent futures left=10 and right=20 into "sum=30"; and the four-stage pipeline combined thenCompose, thenCombine, and thenApply in sequence to produce "final=1050". All four futures completed successfully; if any stage had thrown, the exception would have propagated as a CompletionException on the corresponding get() call.
Common Mistakes to Avoid
First, calling thenApply on a function that returns a CompletableFuture. This produces CompletableFuture<CompletableFuture<R>>; you almost certainly wanted thenCompose. The compiler will not warn you, because both calls type-check, but the runtime value will be a future of a future, which makes downstream code hard to write.
Second, blocking on get() inside a function passed to thenApply. This defeats the async design: the future's completing thread blocks, which can stall other work on the same pool. If you must block, do it on a separate dedicated pool (pass a custom Executor to thenApplyAsync), or restructure the pipeline to use thenCompose with a future-returning transformation.
Third, using thenApplyAsync for trivial transformations. The Async variants add task-submission overhead and a context switch; for cheap functions like n -> n * 2 the non-Async thenApply is faster. Reserve Async variants for genuinely expensive functions or when you need to escape a thread (for example, when the source completes on a Netty IO thread and the function would block it).
Fourth, forgetting to handle exceptions. An unhandled exceptionally-completed future will throw CompletionException when you call get(); in a fire-and-forget pipeline this becomes a silently swallowed error because no one is calling get(). Always attach an exceptionally or whenComplete at the end of the pipeline so failures are at least logged, even if not recovered.
Real-World Applications
Java CompletableFuture chaining is the standard Java idiom for async service composition. Spring Framework 6 uses it in WebClient and @Async return types; the Spring AsyncReturnTypeConverter recognises CompletableFuture<T> as a valid async return type for controller methods. Apache HttpClient 5's async API returns CompletableFuture for HTTP calls, so you can chain retries and JSON deserialisation fluently. gRPC-Java's ListenableFuture-to-CompletableFuture bridge lets you compose gRPC calls with thenApply and thenCompose. JDBC's newer async drivers, Hibernate Reactive, and Mutiny (the Quarkus reactive toolkit) all interoperate with CompletableFuture at their boundaries.
In the database world, Reactive Relational Database Connectivity (R2DBC) drivers return CompletableFuture-derived reactive types. In the messaging world, Kafka's producer.send returns a future that you can chain through thenApply to log the offset, and the consumer API can return CompletableFuture for offset commits. The Java 8 parallel-stream implementation itself uses CompletableFuture internally for its fork-join decomposition of the terminal operation. Netflix Hystrix (now superseded by Resilience4j) wraps every command in a CompletableFuture that supports fallbacks, timeouts, and circuit-breaker semantics through chained exceptionally handlers.
Conclusion
Java CompletableFuture chaining is the modern way to compose asynchronous work in Java without callback hell. The three core methods, thenApply, thenCompose, and thenCombine, cover the three fundamental shapes of async composition: synchronous transform, async bind, and pairwise merge. We walked through the supplyAsync entry point, the difference between the non-Async and Async variants, and the exception-handling trio of exceptionally, handle, and whenComplete. To go deeper, study the full method table in the java.util.concurrent.CompletableFuture javadoc, then read Brian Goetz's JSR-335 design notes on the CompletableFuture monad. After that, the natural next topics are the Java 9 Reactive Flow API (JEP 266) for streams of events and the Project Reactor Core library for a richer reactive toolkit.
Comments
Comments
Post a Comment