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.
CompletableFuture<String> greeting = CompletableFuture .supplyAsync(() -> "hello") .thenApply(String::toUpperCase); System.out.println(greeting.join()); // HELLO
Try it
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.
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
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.
thenApplyvsthenCompose. If the function returns aCompletableFuture, usethenCompose, otherwise you get a nestedCompletableFuture<CompletableFuture<...>>.- Exceptions propagate downstream. A failed stage skips later
thenApplystages and arrives as aCompletionExceptionwrapping the original cause. Handlers attached to a future that failed insidesupplyAsync(as in the example above) also see the wrapper, while a future failed bycompleteExceptionally(ex)hands the raw exception to handlers attached directly to it. CallgetCause()when in doubt. join()vsget().join()is unchecked and is convenient inside lambdas;get()throws checked exceptions.allOfreturnsCompletableFuture<Void>. Read each input future's result yourself afterwards.cancel()does not interrupt the running computation; the future just completes withCancellationException.- Do not block inside callbacks (no
get()in athenApplyon the same pool); that can deadlock a small pool. - Prefer
...Asyncvariants with an executor if a stage is slow and you do not want it to run on the thread that completed the previous one.
Related
Future,ExecutorService,Callable, Virtual threads- Lessons: CompletableFuture, Executors