CKTIS / Java
CompletableFuture — composing asynchronous computations
CompletableFuture<T> represents a future result and lets you connect dependent stages without blocking after every step. Learn transformations, composition, result combination, error recovery, and timeouts in Java SE 21.
Version: Java SE 21; repository runtime, production runtime not attested
Syntax
CompletableFuture<T> future = CompletableFuture.supplyAsync(supplier, executor);
CompletableFuture<U> mapped = future.thenApply(mapper);
CompletableFuture<U> composed = future.thenCompose(asyncMapper);
T result = future.join();CompletableFuture<T> combines a Future<T> result with CompletionStage<T> stages. CompletableFuture.supplyAsync submits a computation; CompletableFuture.completedFuture creates an already completed result. CompletableFuture.completeExceptionally completes an unfinished future with an error. Scope: Java SE 21; repository runtime, production runtime not attested.
CompletableFuture.thenApply transforms a successful result; it does not guarantee a separate thread. CompletableFuture.thenApplyAsync submits the function for execution by an executor. The default is ForkJoinPool.commonPool(); when parallelism is below two, a thread is created for each task. You can supply an executor explicitly. CompletableFuture.thenCompose flattens a function returning another stage instead of creating a nested result. CompletableFuture.thenCombine combines values after both stages succeed.
CompletableFuture.exceptionally computes a replacement value only after failure. CompletableFuture.allOf waits for every stage, returns CompletableFuture<Void>, and propagates failure if any stage fails; it does not collect values. CompletableFuture.anyOf returns CompletableFuture<Object> with the result or failure of one completing stage—not necessarily a success. It does not cancel the remaining tasks.
CompletableFuture.join and CompletableFuture.get block until completion. Failure is usually wrapped in unchecked CompletionException or checked ExecutionException, respectively; get can also throw InterruptedException. Cancellation throws CancellationException. Avoid blocking inside dependent tasks.
CompletableFuture.completeOnTimeout completes the same future with a fallback value, whereas CompletableFuture.orTimeout completes it with TimeoutException, unless it has already completed. Neither method stops the underlying computation. In contrast, get(timeout, unit) limits only the caller's wait.
Examples
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
try (var executor = Executors.newFixedThreadPool(2)) {
var base = CompletableFuture.supplyAsync(() -> 20, executor);
var result = base
.thenApply(n -> n + 1)
.thenCompose(n -> CompletableFuture.completedFuture(n * 2))
.thenCombine(CompletableFuture.completedFuture(8), Integer::sum);
var failed = new CompletableFuture<Integer>();
failed.completeExceptionally(new IllegalStateException("unavailable"));
var recovered = failed.exceptionally(error -> -1);
CompletableFuture.allOf(result, recovered).join();
System.out.println("result=" + result.join());
System.out.println("recovered=" + recovered.join());
}
}
}Result
result=50 recovered=-1
The displayed code and declared result were verified in an isolated environment using the method recorded in the verification evidence for this exact version.