CompletableFuture composition
What you will learn
A CompletableFuture represents one eventual result, including failure. Compose dependent operations instead of making a worker wait for another job. CompletionStage describes the composition contract; CompletableFuture also provides explicit completion and Future-style waiting.
- Transform a result and flatten a dependent asynchronous operation.
- Combine independent results and distinguish allOf from anyOf.
- Explain which dependencies must complete before a continuation runs.
Each example is a complete Main.java file. Use a fresh lab-owned directory: javac --release 21 -proc:none Main.java, then java Main. Only finite reviewed tasks are started. Use the included bounded pool and shutdown helpers where applicable. The fixture runner also enforces a process deadline.
Transform a completed value
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main {
public static void main(String[] args) throws Exception { CompletableFuture<Integer> price = CompletableFuture.completedFuture(120); CompletionStage<Integer> total = price.thenApply(p -> p + 30); System.out.println(total.toCompletableFuture().join()); }}Expected output:
150The stage already contains the price. The continuation computes a new value; the original price remains 120.
Transform or compose
Use thenApply when a function returns an ordinary value and thenCompose when it returns another CompletionStage. The latter follows the inner stage and avoids nesting. thenCombine requires two successful inputs; it does not start either input. A stage may already be complete when a continuation is attached. Non-async callbacks are not promised a separate thread. Keep them short and avoid waiting for another task in them.
Fan-out and fan-in
allOf returns CompletableFuture<Void>; it completes when all supplied futures complete and fails if any fails. Retrieve individual results only after successful aggregation; an empty allOf is already complete. anyOf returns CompletableFuture<Object> for the first completion, including failure; it is not first successful result and does not cancel other inputs. An empty anyOf remains incomplete. Neither API establishes a particular winner when completions race. The examples explicitly complete futures in a known order.
Choose a workflow
Imperative blocking code is often simplest for sequential work; asynchronous composition is useful when independent operations can overlap or callers must avoid blocking. A future produces one completion, not a stream of messages. Reactive designs such as Flow use publishers, subscribers and subscriptions for repeated values with demand control. CompletableFuture alone does not provide stream backpressure. Use explicit submission limits and handle overload; this chapter makes no throughput claims.
Flatten a dependent lookup
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main {
public static void main(String[] args) throws Exception { CompletableFuture<String> order = new CompletableFuture<>(); CompletableFuture<Integer> stock = new CompletableFuture<>(); CompletableFuture<Integer> result = order.thenCompose(id -> stock); order.complete("A-10"); System.out.println(result.isDone()); stock.complete(8); System.out.println(result.join()); }}Expected output:
false8The order must complete before the dependent stage is selected. The result remains pending until stock completes. This simulates a lookup without network access.
Combine independent results
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main {
public static void main(String[] args) throws Exception { CompletableFuture<Integer> price = new CompletableFuture<>(); CompletableFuture<Integer> shipping = new CompletableFuture<>(); CompletableFuture<Integer> total = price.thenCombine(shipping, Integer::sum); shipping.complete(15); System.out.println(total.isDone()); price.complete(80); System.out.println(total.join()); }}Expected output:
false95Both inputs must succeed. Their completion order does not alter this sum.
Compare allOf and anyOf
import java.util.concurrent.*;import java.util.concurrent.atomic.*;import java.util.concurrent.locks.*;public class Main {
public static void main(String[] args) throws Exception { CompletableFuture<String> a = new CompletableFuture<>(), b = new CompletableFuture<>(); CompletableFuture<Void> all = CompletableFuture.allOf(a, b); CompletableFuture<Object> first = CompletableFuture.anyOf(a, b); b.complete("warehouse B"); System.out.println(first.join()); System.out.println(all.isDone()); a.complete("warehouse A"); all.join(); System.out.println(a.join() + ", " + b.join()); }}Expected output:
warehouse Bfalsewarehouse A, warehouse BThe first completion does not terminate the other input. allOf provides a completion signal, not a list. The individual joins are safe here because both inputs have completed successfully.
Common mistakes
Do not use thenApply with a stage-returning function when you need a flattened result. Do not treat anyOf as first successful answer or allOf as a list of values. Avoid blocking on a pending child from a worker in the same constrained pool.
Practice
Create two incomplete integer futures for item price and tax. Combine them with thenCombine, complete tax with 12 first and price with 60 second. Print whether the combined future is done after tax and then print the total.
Expected output:
false72Compare your answer with the manual practice criteria.
Official reading: CompletableFuture · CompletionStage · Flow. Java 25 execution remains unverified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
CompletableFuture composition — knowledge check
Original asynchronous workflow questions. Java 21-compatible scope.
Which operation flattens a stage returned by a function?
When can thenCombine invoke its combiner?
What is the result type of allOf?
Does anyOf guarantee a successful result?
Which abstraction provides demand control for repeated messages?