Skip to content
Tutorials Center
My learning

Topics

Java Reference ยท Concurrency

The CompletableFuture class

Reference for CompletableFuture: supplyAsync, thenApply, thenCompose, thenCombine, allOf, error handling with exceptionally and handle, and timeouts.

CompletableFuture<T> is a Future you can finish by hand and, more importantly, chain. You describe a pipeline: "get this value asynchronously, then transform it, then combine it with another result, and if anything fails, use a fallback". Each stage runs when the previous one completes, without anyone blocking a thread to wait for it.

It implements both Future<T> and CompletionStage<T>; most of the useful methods come from the latter. Methods without Async in the name run the next stage in whichever thread completed the previous one (or in the caller, if it was already complete); the ...Async variants hand the stage to an executor.

Java
CompletableFuture<String> greeting = CompletableFuture
        .supplyAsync(() -> "hello")
        .thenApply(String::toUpperCase);
System.out.println(greeting.join());   // HELLO

Try it

Java Chaining, composing and combining

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Java Errors, fallbacks and timeouts

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Syntax

Java
public class CompletableFuture<T> implements Future<T>, CompletionStage<T>
Method Description
static supplyAsync(Supplier<U>[, Executor]) Runs a task that returns a value. Without an executor it uses the common pool.
static runAsync(Runnable[, Executor]) Runs a task without a result.
static completedFuture(U) An already completed future.
thenApply(Function) Transforms the result (like map).
thenCompose(Function<T, CompletionStage<U>>) Chains a dependent async step (like flatMap).
thenCombine(CompletionStage, BiFunction) Combines two independent results.
thenAccept(Consumer), thenRun(Runnable) Terminal stages with no result.
exceptionally(Function<Throwable,T>) Recovers from a failure with a value.
handle(BiFunction<T,Throwable,U>), whenComplete(BiConsumer) Sees both outcomes; handle can change the result, whenComplete cannot.
static allOf(CompletableFuture<?>...), anyOf(...) Completes when all (or the first) complete.
get(), join(), getNow(T) Retrieve the result. join() throws unchecked CompletionException.
complete(T), completeExceptionally(Throwable) Finish by hand; returns false if already complete.
orTimeout(long, TimeUnit), completeOnTimeout(T, long, TimeUnit) Java 9+. Fail with TimeoutException or complete with a default.

Usage notes

  • Pass your own executor for blocking work. The common pool has about one thread per CPU; blocking tasks in it starve other users of the pool. On a single-CPU machine the common pool is not used for async tasks, and each one gets a fresh thread.
  • thenApply vs thenCompose. If the function returns a CompletableFuture, use thenCompose, otherwise you get a nested CompletableFuture<CompletableFuture<...>>.
  • Exceptions propagate downstream. A failed stage skips later thenApply stages and arrives as a CompletionException wrapping the original cause. Handlers attached to a future that failed inside supplyAsync (as in the example above) also see the wrapper, while a future failed by completeExceptionally(ex) hands the raw exception to handlers attached directly to it. Call getCause() when in doubt.
  • join() vs get(). join() is unchecked and is convenient inside lambdas; get() throws checked exceptions.
  • allOf returns CompletableFuture<Void>. Read each input future's result yourself afterwards.
  • cancel() does not interrupt the running computation; the future just completes with CancellationException.
  • Do not block inside callbacks (no get() in a thenApply on the same pool); that can deadlock a small pool.
  • Prefer ...Async variants with an executor if a stage is slow and you do not want it to run on the thread that completed the previous one.