CompletionStage Interface in Java: Composing Asynchronous Steps
CompletionStage describes one step of an asynchronous computation that runs when another step completes. Instead of blocking on get(), you attach the next action, and the stages form a pipeline.
This tutorial explains the main method families, how to combine stages, and how to recover from failures. The concrete class you will use is CompletableFuture.
1. What Is CompletionStage?
CompletionStage<T> is an interface in java.util.concurrent, added in Java 8. A stage completes with a value of type T or with an exception, and triggers the stages that depend on it.
Unlike Future, it has no blocking get() and no cancel(). Its methods each return a new CompletionStage, which is what lets you chain them. toCompletableFuture() converts a stage when you finally need to wait for it.
2. CompletionStage Hierarchy
Swipe sideways to see the whole diagram.
CompletableFuture(class): The JDK's implementation; it is both a CompletionStage and a Future.Future(interface): Not a parent of CompletionStage; CompletableFuture implements both, which adds blocking access.
3. Method Families
| Methods | Use when the next step… |
|---|---|
thenApply(fn) | transforms the value: T to U. |
thenAccept(action) / thenRun(action) | consumes the value, or just runs afterwards. |
thenCompose(fn) | is itself asynchronous and returns a CompletionStage<U>. |
thenCombine(other, fn) | needs the results of two independent stages. |
applyToEither / acceptEither | should use whichever of two stages finishes first. |
exceptionally / exceptionallyCompose | should recover from a failure (the latter since Java 12). |
handle(fn) / whenComplete(action) | must run on success and failure alike. |
Most methods also come in …Async versions. Without an executor argument, CompletableFuture runs them on ForkJoinPool.commonPool(); pass your own executor to control where they run.
4. Example: A Non-Blocking Checkout Pipeline
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CheckoutPipeline {
record Cart(String customer, int itemsCents) {}
// Each "remote call" returns a CompletionStage instead of blocking
static CompletionStage<Cart> loadCart(ExecutorService io) {
return CompletableFuture.supplyAsync(() -> new Cart("C-1042", 8_950), io);
}
static CompletionStage<Integer> shippingCents(Cart cart, ExecutorService io) {
return CompletableFuture.supplyAsync(() -> cart.itemsCents() >= 5_000 ? 0 : 499, io);
}
static CompletionStage<Integer> loyaltyDiscountCents(ExecutorService io) {
return CompletableFuture.supplyAsync(() -> 750, io);
}
public static void main(String[] args) {
try (ExecutorService io = Executors.newFixedThreadPool(4)) {
CompletionStage<Cart> cart = loadCart(io);
CompletionStage<Integer> total = cart
.thenCompose(c -> shippingCents(c, io) // async step that depends on the cart
.thenApply(ship -> c.itemsCents() + ship)) // transform the value
.thenCombine(loyaltyDiscountCents(io), (sum, discount) -> sum - discount); // join two stages
total.thenAccept(cents -> System.out.printf("Order total: %.2f EUR%n", cents / 100.0))
.toCompletableFuture()
.join(); // wait only at the very end
}
}
}
Order total: 82.00 EUR
How the code works
- Each service method returns a
CompletionStage, so the caller never blocks while it runs. thenCompose()starts the shipping lookup once the cart is loaded. UsingthenApply()here would produce a nestedCompletionStage<CompletionStage<Integer>>.thenApply()adds the shipping cost to the item total.thenCombine()waits for both the subtotal and the loyalty discount, which run independently, and merges them: 89.50 + 0.00 − 7.50.- Only the last line calls
join(), throughtoCompletableFuture(), so the program can finish printing before the executor closes.
5. Example: Recovering from Payment Failures
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionStage;
public class PaymentFallbacks {
static CompletionStage<String> charge(String provider, boolean available) {
return available
? CompletableFuture.completedStage("charged via " + provider)
: CompletableFuture.failedStage(new IllegalStateException(provider + " is down"));
}
public static void main(String[] args) {
// exceptionally: replace a failure with a plain value
String a = charge("CardPay", false)
.exceptionally(ex -> "queued for retry (" + ex.getMessage() + ")")
.toCompletableFuture().join();
System.out.println("exceptionally -> " + a);
// exceptionallyCompose (Java 12+): replace a failure with another async attempt
String b = charge("CardPay", false)
.exceptionallyCompose(ex -> charge("WalletPay", true))
.toCompletableFuture().join();
System.out.println("exceptionallyCompose -> " + b);
// handle: always runs, sees either the result or the exception
String c = charge("CardPay", true)
.handle((ok, ex) -> ex == null ? ok.toUpperCase() : "failed")
.toCompletableFuture().join();
System.out.println("handle -> " + c);
// whenComplete: side effect only, the original outcome passes through unchanged
String d = charge("WalletPay", true)
.whenComplete((ok, ex) -> System.out.println("audit log: " + (ex == null ? "success" : "failure")))
.toCompletableFuture().join();
System.out.println("whenComplete -> " + d);
}
}
exceptionally -> queued for retry (CardPay is down) exceptionallyCompose -> charged via WalletPay handle -> CHARGED VIA CARDPAY audit log: success whenComplete -> charged via WalletPay
How the code works
completedStage()andfailedStage()(Java 9+) create stages that are already finished, which keeps the example easy to follow.exceptionally()runs only on failure and supplies a replacement value.exceptionallyCompose()runs only on failure and supplies a replacement stage, here a second payment provider.handle()always runs and can turn either outcome into a new value.whenComplete()always runs for side effects, such as logging, and passes the original outcome through unchanged.
6. Common Mistakes and Best Practices
thenApplywith an async function. If the function returns a stage, usethenCompose()to avoid nesting.- Blocking in the middle. Calling
join()inside a stage defeats the purpose; block, if at all, only at the edge of the program. - Swallowed failures. An exception skips the following
thenApplystages; addexceptionally()orhandle()where you can recover. - Hidden thread pool.
…Asyncmethods without an executor use the shared common pool; pass a dedicated executor for blocking I/O. - Wrapped exceptions. In dependent stages the error often arrives wrapped in
CompletionException; inspectgetCause().
7. Summary
CompletionStageis one step of an asynchronous pipeline that triggers dependent steps when it completes.- Use
thenApplyto transform,thenComposeto chain async calls, andthenCombineto join two stages. - Recover with
exceptionally,exceptionallyComposeorhandle; log withwhenComplete. CompletableFutureis the standard implementation.
Related Tutorials
8. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between thenApply and thenCompose?
thenApply() takes a function that returns a plain value. thenCompose() takes a function that returns another CompletionStage and flattens it, so you get CompletionStage<U> instead of a nested stage.
Q2. What is the difference between handle and whenComplete?
Both run on success and on failure. handle() returns a new value, so it can recover from an error. whenComplete() is for side effects; the stage it returns completes with the same result or exception as the original.
Q3. Is CompletionStage the same as CompletableFuture?
No. CompletionStage is an interface describing composable stages. CompletableFuture is a class that implements it and also implements Future, adding methods such as complete(), join() and get().
Q4. Which thread runs a non-async stage such as thenApply?
For CompletableFuture, it may run on the thread that completes the previous stage, or on any other thread that calls a completion method; if the previous stage is already complete, that is typically the thread calling thenApply(). Use the …Async variants with an executor when you need control over the thread.
Q5. Can I cancel a CompletionStage?
The interface has no cancel() method. Convert it with toCompletableFuture() and call cancel() there, which completes the stage exceptionally with a CancellationException.