CompletableFuture

A CompletableFuture is a result that will be available later, plus methods that say what should happen next. Steps chain like a stream pipeline, independent work runs in parallel, and errors flow down the chain until something handles them. This page explains how a CompletableFuture runs its stages and on which thread, then builds a timed pipeline, handles errors and timeouts, and shows two traps: cancel does not interrupt, and blocking calls starve the common pool.

Contents

How a CompletableFuture works

A plain Future (Java 5) can only be asked for its result, which blocks. CompletableFuture (Java 8, JEP 155) adds two things. It can be completed by anyone, with complete(value) or completeExceptionally(error). And it implements CompletionStage, about 40 methods that attach the next step: transform the result, start another asynchronous call with it, combine it with another future, or recover from a failure.

Inside, a CompletableFuture has a result field and a stack of dependent actions. Attaching a stage pushes an action onto the stack, or runs it immediately if the result is already there. Completing the future stores the result and pops and runs the waiting actions. That is why a pipeline built in a few lines returns at once: nothing has run yet, the code has only been registered.

Each method comes in up to three forms. thenApply(fn) runs fn in whatever thread completes the previous stage, or in the calling thread if it has already completed. thenApplyAsync(fn) always hands fn to the default async executor, and thenApplyAsync(fn, executor) to the executor you give. The default is ForkJoinPool.commonPool(), unless its parallelism is below 2, in which case each async task gets a new thread.

The main CompletableFuture methods
MethodSinceWhat it doesBest for
supplyAsync, runAsyncJava 8Starts a task and returns its futureThe first step of a pipeline
thenApply, thenAccept, thenRunJava 8Transforms or consumes the resultQuick, non-blocking steps
thenComposeJava 8Starts another future from the result and flattens itDependent asynchronous calls
thenCombineJava 8Combines two independent futuresTwo calls made in parallel
allOf, anyOfJava 8Completes when all, or the first, of many completeFan-out
exceptionally, handle, whenCompleteJava 8Recovers from, maps or observes a failureFallback values and logging
orTimeout, completeOnTimeout, failedFutureJava 9Deadlines and ready-made failed futuresBounding wait time
exceptionallyComposeJava 12Recovers with another futureCalling a backup service
state, resultNow, exceptionNowJava 19Reads a completed future without blockingInspecting results after allOf

The examples were run on JDK 21 on a 2-CPU machine, which matters for the default executor, as the second program shows.

A pipeline: thenApply, thenCompose, thenCombine

A price is computed from a user's score and an exchange rate. Loading the user, loading the score and loading the rate each take 200 ms. The score needs the user, but the rate is independent, so the best possible time is 400 ms, not 600 ms.

Java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Pipeline {

    static void sleep(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }

    record User(int id, String name) {
    }

    static User loadUser(int id) {
        sleep(200);
        return new User(id, "ada");
    }

    static CompletableFuture<Integer> loadScoreAsync(User u, ExecutorService pool) {
        return CompletableFuture.supplyAsync(() -> {
            sleep(200);
            return u.name().length() * 10;
        }, pool);
    }

    static double loadRate() {
        sleep(200);
        return 1.5;
    }

    public static void main(String[] args) {
        try (ExecutorService pool = Executors.newFixedThreadPool(4)) {
            long start = System.nanoTime();

            CompletableFuture<User> user =
                    CompletableFuture.supplyAsync(() -> loadUser(7), pool);
            CompletableFuture<Double> rate =
                    CompletableFuture.supplyAsync(Pipeline::loadRate, pool);

            CompletableFuture<String> result = user
                    .thenApply(u -> new User(u.id(), u.name().toUpperCase()))   // sync transform
                    .thenCompose(u -> loadScoreAsync(u, pool))                  // async next step
                    .thenCombine(rate, (score, r) -> score * r)                 // join two futures
                    .thenApply(total -> "total score " + total);

            System.out.println(result.join());
            System.out.println("took about " + (System.nanoTime() - start) / 100000000 * 100
                    + " ms (user and rate loaded in parallel)");
        }
    }
}

Output:

Output
total score 45.0
took about 400 ms (user and rate loaded in parallel)
  • The pipeline took about 400 ms: the user and the rate loaded at the same time, then the score loaded while the rate was already waiting. The total is the name "ADA" (3 letters) × 10 × 1.5 = 45.0.
  • thenApply is for a plain function from value to value, here upper-casing the name. thenCompose is for a function that itself returns a CompletableFuture. Using thenApply with loadScoreAsync would compile, but give a CompletableFuture<CompletableFuture<Integer>>. The relationship is the same as map and flatMap on streams.
  • thenCombine waits for two futures and merges their results with a two-argument function. It does not start anything; the rate future was already running from its own supplyAsync.
  • join() blocks only at the very end, in main. Inside a pipeline, never call join() or get() on another future; compose it instead.

Which thread runs each stage?

Whether a stage runs in the caller, in the thread that completed the previous stage, or in an executor is the source of many surprises. The program checks each case and reports the default executor on this 2-core machine.

Java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;

public class WhichThread {

    static String where() {
        String name = Thread.currentThread().getName();
        return name.startsWith("ForkJoinPool") ? "common pool" : name;
    }

    public static void main(String[] args) {
        System.out.println("commonPool parallelism: " + ForkJoinPool.getCommonPoolParallelism()
                + " (cores - 1, here " + Runtime.getRuntime().availableProcessors() + " cores)");

        // 1. No executor given: the default async executor
        String def = CompletableFuture.supplyAsync(() -> where()).join();
        System.out.println("supplyAsync, no executor: " + (def.startsWith("Thread-")
                ? "a new Thread per task (commonPool parallelism < 2)" : def));

        try (ExecutorService io = Executors.newFixedThreadPool(2,
                Thread.ofPlatform().name("io-", 1).factory())) {
            // 2. A non-async stage on an already completed future runs in the caller
            CompletableFuture<String> done = CompletableFuture.completedFuture("x");
            System.out.println("thenApply on completed:   " + done.thenApply(v -> where()).join());

            // 3. A non-async stage added before completion runs in the completing thread
            CompletableFuture<String> later = new CompletableFuture<>();
            CompletableFuture<String> stage = later.thenApply(v -> where());
            io.submit(() -> later.complete("y"));
            System.out.println("thenApply, completed by io: " + stage.join());

            // 4. thenApplyAsync with an executor always hops to that executor
            String hop = done.thenApplyAsync(v -> where(), io).join();
            System.out.println("thenApplyAsync(io):       an io thread? " + hop.startsWith("io-"));
        }
    }
}

Output:

Output
commonPool parallelism: 1 (cores - 1, here 2 cores)
supplyAsync, no executor: a new Thread per task (commonPool parallelism < 2)
thenApply on completed:   main
thenApply, completed by io: io-1
thenApplyAsync(io):       an io thread? true
  • The common pool's parallelism is the number of cores minus one, so 1 here. CompletableFuture uses the common pool only if its parallelism is at least 2; otherwise its default executor creates a new thread for every async task. The same program behaves differently on a laptop and on a 2-CPU container.
  • thenApply on a future that was already complete ran on main, the thread that attached it. A slow function there blocks the caller.
  • thenApply attached before completion ran on io-1, the thread that called complete. A cheap step is fine there; a slow one delays whatever that thread was supposed to do next, for example an HTTP client's I/O thread.
  • The Async variant with an executor always moved the step to that executor. Pass an executor explicitly whenever a step is slow or blocking.

Handling errors

When a stage throws, every following stage that needs its value is skipped and the failure travels down the chain until a stage handles it. Each case below parses a string, some of which are not numbers.

Java
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;

public class Errors {

    static int parse(String s) {
        return Integer.parseInt(s);
    }

    public static void main(String[] args) {
        // exceptionally: replace a failure with a fallback value
        int a = CompletableFuture.supplyAsync(() -> parse("x"))
                .exceptionally(e -> {
                    System.out.println("exceptionally saw: " + e.getClass().getSimpleName()
                            + " caused by " + e.getCause().getClass().getSimpleName());
                    return -1;
                })
                .join();
        System.out.println("a = " + a);

        // handle: sees either the result or the error
        String b = CompletableFuture.supplyAsync(() -> parse("42"))
                .handle((value, error) -> error == null ? "ok " + value : "failed")
                .join();
        System.out.println("b = " + b);

        // Steps after a failure are skipped
        CompletableFuture<Integer> broken = CompletableFuture.supplyAsync(() -> parse("?"))
                .thenApply(n -> {
                    System.out.println("never printed");
                    return n * 2;
                });
        try {
            broken.join();
        } catch (CompletionException e) {
            System.out.println("join threw CompletionException wrapping "
                    + e.getCause().getClass().getSimpleName());
        }

        // whenComplete: observe (for logging) without changing the outcome
        CompletableFuture<Integer> logged = CompletableFuture.supplyAsync(() -> parse("7x"))
                .whenComplete((v, e) -> System.out.println("whenComplete saw error: "
                        + (e == null ? "none" : e.getCause().getMessage())));
        System.out.println("after whenComplete, still failed: "
                + logged.isCompletedExceptionally());

        // exceptionallyCompose (Java 12): recover with another async step, e.g. a fallback call
        String c = CompletableFuture.<String>failedFuture(new IllegalStateException("primary down"))
                .exceptionallyCompose(e -> CompletableFuture.supplyAsync(() -> "from backup"))
                .join();
        System.out.println("c = " + c);

        // get() wraps in ExecutionException, join() in CompletionException
        try {
            CompletableFuture.supplyAsync(() -> parse("?")).get();
        } catch (ExecutionException e) {
            System.out.println("get threw ExecutionException wrapping "
                    + e.getCause().getClass().getSimpleName());
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

Output:

Output
exceptionally saw: CompletionException caused by NumberFormatException
a = -1
b = ok 42
join threw CompletionException wrapping NumberFormatException
whenComplete saw error: For input string: "7x"
after whenComplete, still failed: true
c = from backup
get threw ExecutionException wrapping NumberFormatException
  • exceptionally replaced the failure with -1. The exception it received was a CompletionException whose cause was the NumberFormatException: failures from an earlier stage arrive wrapped. Unwrap with getCause() before deciding what to do.
  • handle receives both the value and the error, one of which is null, and always produces a new value. Use it when success and failure map to the same type, as with "ok 42".
  • The stage after the failed parse never printed; join() threw CompletionException. get() throws the checked ExecutionException instead, as the last line shows; otherwise the two are the same.
  • whenComplete saw the error but left the future failed. It is for logging and metrics, not recovery.
  • exceptionallyCompose (Java 12) recovered by starting another future, the "backup" call, which is not possible with exceptionally without blocking.

Fan-out: allOf and anyOf

Three pages load in 300, 100 and 200 ms, and three mirrors answer in 300, 50 and 200 ms. The delays are far enough apart that the winner is the same in every run.

Java
import java.util.List;
import java.util.concurrent.CompletableFuture;

public class AllAnyOf {

    static CompletableFuture<String> fetch(String name, long ms) {
        return CompletableFuture.supplyAsync(() -> {
            try {
                Thread.sleep(ms);
            } catch (InterruptedException e) {
                Thread.currentThread().interrupt();
            }
            return name;
        });
    }

    public static void main(String[] args) {
        List<CompletableFuture<String>> pages = List.of(
                fetch("home", 300), fetch("about", 100), fetch("blog", 200));

        // allOf: wait for every future, then collect the results
        CompletableFuture.allOf(pages.toArray(new CompletableFuture<?>[0])).join();
        List<String> all = pages.stream().map(CompletableFuture::join).toList();
        System.out.println("allOf results, in list order: " + all);

        // anyOf: the first to finish wins
        Object first = CompletableFuture.anyOf(
                fetch("mirror-1", 300), fetch("mirror-2", 50), fetch("mirror-3", 200)).join();
        System.out.println("anyOf winner: " + first);
    }
}

Output:

Output
allOf results, in list order: [home, about, blog]
anyOf winner: mirror-2
  • allOf returns a CompletableFuture<Void>: it signals that all are done but carries no values. The results are then read from the original futures, in list order, regardless of which finished first. If any input fails, the allOf future fails too, but only after all of them have completed.
  • anyOf completes with the first future to complete, here mirror-2 after 50 ms. Its type is CompletableFuture<Object>, so a cast is needed, and a fast failure also wins: if the first mirror to answer fails, anyOf fails. For "first success", collect the futures and complete your own future from thenAccept on each.
  • The losing mirrors keep running after anyOf completes. Nothing cancels them, and cancelling would not stop them anyway, as the next section shows.

Timeouts and the cancel trap

Java 9 added two deadlines: orTimeout fails the future and completeOnTimeout supplies a value. The third case is a trap that catches people who know Future.cancel from executors.

Java
import java.util.concurrent.CancellationException;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;

public class CancelAndTimeout {

    public static void main(String[] args) throws InterruptedException {
        try (ExecutorService pool = Executors.newFixedThreadPool(2)) {
            // 1. orTimeout (Java 9): fail the future with TimeoutException
            CompletableFuture<Integer> slow =
                    CompletableFuture.supplyAsync(() -> work(2000), pool);
            try {
                slow.orTimeout(200, TimeUnit.MILLISECONDS).join();
            } catch (CompletionException e) {
                System.out.println("1. orTimeout: " + e.getCause().getClass().getSimpleName());
            }

            // 2. completeOnTimeout (Java 9): use a default value instead
            int value = CompletableFuture.supplyAsync(() -> work(2000), pool)
                    .completeOnTimeout(-1, 200, TimeUnit.MILLISECONDS).join();
            System.out.println("2. completeOnTimeout gave " + value);

        }
        try (ExecutorService pool = Executors.newFixedThreadPool(1)) {
            // 3. The trap: cancel(true) does NOT interrupt the running task
            AtomicBoolean finished = new AtomicBoolean();
            CompletableFuture<Void> job = CompletableFuture.runAsync(() -> {
                work(500);
                finished.set(true);                   // runs even though cancelled
            }, pool);
            Thread.sleep(100);
            System.out.println("3. cancel(true) returned " + job.cancel(true)
                    + ", isCancelled " + job.isCancelled());
            try {
                job.join();
            } catch (CancellationException e) {
                System.out.println("3. join: CancellationException");
            }
            Thread.sleep(600);
            System.out.println("3. but the task ran to the end anyway: " + finished.get());
        }
    }

    static int work(long ms) {
        try {
            Thread.sleep(ms);
        } catch (InterruptedException e) {
            System.out.println("   (interrupted)");
            return 0;
        }
        return 1;
    }
}

Output:

Output
1. orTimeout: TimeoutException
2. completeOnTimeout gave -1
3. cancel(true) returned true, isCancelled true
3. join: CancellationException
3. but the task ran to the end anyway: true
  1. orTimeout(200 ms) completed the future with TimeoutException, which join delivered wrapped in CompletionException.
  2. completeOnTimeout(-1, 200 ms) completed it with -1 instead, a fallback value with no exception handling.
  3. cancel(true) returned true and the future reported itself cancelled, but the task kept running and finished its work 500 ms later. The Javadoc says the mayInterruptIfRunning argument "has no effect", because a CompletableFuture does not know which thread, if any, is computing it. The same is true of the timeouts: the two slow tasks in cases 1 and 2 also ran for their full 2 seconds.

To really stop the work, the task must check a flag or be interrupted through the executor: submit it with ExecutorService.submit and cancel that Future, or use the cancellation built into structured concurrency.

Blocking calls and the common pool

The common pool is sized for CPU work: on a machine with 4 cores it has 3 threads, shared with parallel streams and every library that uses it. Twenty blocking calls of 100 ms each are sent to it and to two alternatives. To show the 4-core behaviour on this 2-core machine, the program runs with -Djava.util.concurrent.ForkJoinPool.common.parallelism=3.

Java
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.IntStream;

public class BlockingInCommonPool {

    static int call(int i) {
        try {
            Thread.sleep(100);                        // a blocking remote call
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
        return i;
    }

    public static void main(String[] args) {
        System.out.println("20 blocking calls of 100 ms each; commonPool parallelism "
                + ForkJoinPool.getCommonPoolParallelism());
        time("ForkJoinPool.commonPool()", ForkJoinPool.commonPool());
        try (ExecutorService fixed = Executors.newFixedThreadPool(20)) {
            time("newFixedThreadPool(20)", fixed);
        }
        try (ExecutorService virtual = Executors.newVirtualThreadPerTaskExecutor()) {
            time("virtual thread per task", virtual);
        }
    }

    static void time(String name, Executor executor) {
        long t0 = System.nanoTime();
        List<CompletableFuture<Integer>> fs = IntStream.range(0, 20)
                .mapToObj(i -> CompletableFuture.supplyAsync(() -> call(i), executor))
                .toList();
        int sum = CompletableFuture.allOf(fs.toArray(CompletableFuture[]::new))
                .thenApply(v -> fs.stream().mapToInt(CompletableFuture::join).sum())
                .join();
        long ms = (System.nanoTime() - t0) / 1000000;
        System.out.printf("%-26s sum %d, about %,d ms%n", name, sum, Math.round(ms / 100.0) * 100);
    }
}

Output (2-CPU Linux machine, JDK 21, common pool parallelism set to 3):

Output
20 blocking calls of 100 ms each; commonPool parallelism 3
ForkJoinPool.commonPool()  sum 190, about 700 ms
newFixedThreadPool(20)     sum 190, about 100 ms
virtual thread per task    sum 190, about 100 ms
  • On the common pool the calls took about 700 ms: 20 calls on 3 threads is 7 waves of 100 ms. While they ran, every parallel stream and every other default async stage in the JVM was waiting for those 3 threads.
  • A dedicated pool of 20 threads and a virtual thread per task both finished in about 100 ms, the time of one call.
  • Rule: pass an executor to supplyAsync for anything that blocks, such as JDBC, file I/O or a blocking HTTP client. Since Java 21, Executors.newVirtualThreadPerTaskExecutor() is a good default for such calls.

Choosing the right method

CompletableFuture recipes
SituationUse
Start a blocking callsupplyAsync(task, executor) with your own executor
Transform a resultthenApply
The next step is itself asynchronousthenCompose
Two independent callsStart both, then thenCombine
Many calls, need all resultsallOf, then join each future in the callback
Fallback value on failureexceptionally or handle
Fallback call on failureexceptionallyCompose
Logging without changing the resultwhenComplete
DeadlineorTimeout or completeOnTimeout, remembering the task keeps running
Cancellable workExecutorService.submit or structured concurrency

See ExecutorService for executors, ForkJoinPool for the common pool, and Reactor for streams of many asynchronous values rather than one.