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 FutureCompletableFuturecomplete(value)completeExceptionally(error)CompletionStage
Inside, a CompletableFuture
Each method comes in up to three forms. thenApply(fn)fnthenApplyAsync(fn)fnthenApplyAsync(fn, executor)ForkJoinPool.commonPool()
| Method | Since | What it does | Best for |
|---|---|---|---|
supplyAsyncrunAsync | Java 8 | Starts a task and returns its future | The first step of a pipeline |
thenApplythenAcceptthenRun | Java 8 | Transforms or consumes the result | Quick, non-blocking steps |
thenCompose | Java 8 | Starts another future from the result and flattens it | Dependent asynchronous calls |
thenCombine | Java 8 | Combines two independent futures | Two calls made in parallel |
allOfanyOf | Java 8 | Completes when all, or the first, of many complete | Fan-out |
exceptionallyhandlewhenComplete | Java 8 | Recovers from, maps or observes a failure | Fallback values and logging |
orTimeoutcompleteOnTimeoutfailedFuture | Java 9 | Deadlines and ready-made failed futures | Bounding wait time |
exceptionallyCompose | Java 12 | Recovers with another future | Calling a backup service |
stateresultNowexceptionNow | Java 19 | Reads a completed future without blocking | Inspecting 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.
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:
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.
is for a plain function from value to value, here upper-casing the name.thenApply is for a function that itself returns athenCompose . UsingCompletableFuture withthenApply would compile, but give aloadScoreAsync . The relationship is the same asCompletableFuture<CompletableFuture<Integer>> andmap on streams.flatMap 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 ownthenCombine .supplyAsync blocks only at the very end, injoin() . Inside a pipeline, never callmain orjoin() on another future; compose it instead.get()
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.
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:
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.
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.CompletableFuture on a future that was already complete ran onthenApply , the thread that attached it. A slow function there blocks the caller.main attached before completion ran onthenApply , the thread that calledio-1 . 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.complete- The
variant with an executor always moved the step to that executor. Pass an executor explicitly whenever a step is slow or blocking.Async
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.
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:
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
replaced the failure with -1. The exception it received was aexceptionally whose cause was theCompletionException : failures from an earlier stage arrive wrapped. Unwrap withNumberFormatException before deciding what to do.getCause() 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".handle- The stage after the failed parse never printed;
threwjoin() .CompletionException throws the checkedget() instead, as the last line shows; otherwise the two are the same.ExecutionException saw the error but left the future failed. It is for logging and metrics, not recovery.whenComplete (Java 12) recovered by starting another future, the "backup" call, which is not possible withexceptionallyCompose without blocking.exceptionally
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.
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:
allOf results, in list order: [home, about, blog]
anyOf winner: mirror-2
returns aallOf : 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, theCompletableFuture<Void> future fails too, but only after all of them have completed.allOf completes with the first future to complete, here mirror-2 after 50 ms. Its type isanyOf , so a cast is needed, and a fast failure also wins: if the first mirror to answer fails,CompletableFuture<Object> fails. For "first success", collect the futures and complete your own future fromanyOf on each.thenAccept- The losing mirrors keep running after
completes. Nothing cancels them, and cancelling would not stop them anyway, as the next section shows.anyOf
Timeouts and the cancel trap
Java 9 added two deadlines: orTimeoutcompleteOnTimeoutFuture.cancel
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:
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
completed the future withorTimeout(200 ms) , whichTimeoutException delivered wrapped injoin .CompletionException completed it with -1 instead, a fallback value with no exception handling.completeOnTimeout(-1, 200 ms) returned true and the future reported itself cancelled, but the task kept running and finished its work 500 ms later. The Javadoc says thecancel(true) argument "has no effect", because amayInterruptIfRunning 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.CompletableFuture
To really stop the work, the task must check a flag or be interrupted through the executor: submit it with ExecutorService.submitFuture
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
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):
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
for anything that blocks, such as JDBC, file I/O or a blocking HTTP client. Since Java 21,supplyAsync is a good default for such calls.Executors.newVirtualThreadPerTaskExecutor()
Choosing the right method
| Situation | Use |
|---|---|
| Start a blocking call | supplyAsync(task, executor) |
| Transform a result | thenApply |
| The next step is itself asynchronous | thenCompose |
| Two independent calls | Start both, then thenCombine |
| Many calls, need all results | allOfjoin |
| Fallback value on failure | exceptionallyhandle |
| Fallback call on failure | exceptionallyCompose |
| Logging without changing the result | whenComplete |
| Deadline | orTimeoutcompleteOnTimeout |
| Cancellable work | ExecutorService.submit |
See