00:00

CompletionStage Interface in Java: Composing Asynchronous Steps

Last updated:

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

CompletionStage interface hierarchyCompletableFuture implements both CompletionStage and Future.«interface»CompletionStage<T>this pagethenApply(…), thenCompose(…)thenCombine(…), thenAccept(…)exceptionally(…), handle(…)toCompletableFuture()«interface»Future<T>get(), cancel(…)isDone()«class»CompletableFuture<T>supplyAsync(…), runAsync(…)complete(T), join()implementsinterfaceclass

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

MethodsUse 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 / acceptEithershould use whichever of two stages finishes first.
exceptionally / exceptionallyComposeshould 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

CheckoutPipeline.java
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
        }
    }
}
Output
Order total: 82.00 EUR

How the code works

  1. Each service method returns a CompletionStage, so the caller never blocks while it runs.
  2. thenCompose() starts the shipping lookup once the cart is loaded. Using thenApply() here would produce a nested CompletionStage<CompletionStage<Integer>>.
  3. thenApply() adds the shipping cost to the item total.
  4. thenCombine() waits for both the subtotal and the loyalty discount, which run independently, and merges them: 89.50 + 0.00 − 7.50.
  5. Only the last line calls join(), through toCompletableFuture(), so the program can finish printing before the executor closes.

5. Example: Recovering from Payment Failures

PaymentFallbacks.java
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);
    }
}
Output
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

  1. completedStage() and failedStage() (Java 9+) create stages that are already finished, which keeps the example easy to follow.
  2. exceptionally() runs only on failure and supplies a replacement value.
  3. exceptionallyCompose() runs only on failure and supplies a replacement stage, here a second payment provider.
  4. handle() always runs and can turn either outcome into a new value.
  5. whenComplete() always runs for side effects, such as logging, and passes the original outcome through unchanged.

6. Common Mistakes and Best Practices

  • thenApply with an async function. If the function returns a stage, use thenCompose() 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 thenApply stages; add exceptionally() or handle() where you can recover.
  • Hidden thread pool. …Async methods 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; inspect getCause().

7. Summary

  • CompletionStage is one step of an asynchronous pipeline that triggers dependent steps when it completes.
  • Use thenApply to transform, thenCompose to chain async calls, and thenCombine to join two stages.
  • Recover with exceptionally, exceptionallyCompose or handle; log with whenComplete.
  • CompletableFuture is the standard implementation.

Related Tutorials

8. References