CompletableFuture
A Future asks a program to block: the only way to use its value is to wait for it. CompletableFuture is the same idea with a way to say what to do next, so a chain of dependent steps is written as a chain of calls and the value moves through it as it becomes available.
supplyAsync and thenApply
supplyAsync runs a task that returns a value on another thread and answers the future of it. thenApply adds a step that will run when the value arrives, and join waits for the end of the chain and answers its value:
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class Futures {
public static void main(String[] args) throws Exception {
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 20);
System.out.println("thenApply: " + future.thenApply(n -> n * 2).join());
CompletableFuture<String> left = CompletableFuture.supplyAsync(() -> "Ada");
CompletableFuture<Integer> right = CompletableFuture.supplyAsync(() -> 36);
System.out.println("thenCombine: " + left.thenCombine(right, (name, age) -> name + " " + age).join());
CompletableFuture<Integer> a = CompletableFuture.supplyAsync(() -> 1);
CompletableFuture<Integer> b = CompletableFuture.supplyAsync(() -> 2);
CompletableFuture<Integer> c = CompletableFuture.supplyAsync(() -> 3);
CompletableFuture<Void> all = CompletableFuture.allOf(a, b, c);
all.join();
int sum = a.join() + b.join() + c.join();
System.out.println("allOf sum: " + sum);
CompletableFuture<String> failed = CompletableFuture.<String>supplyAsync(() -> {
throw new IllegalStateException("boom");
}).exceptionally(error -> "recovered: " + error.getCause().getMessage());
System.out.println("exceptionally: " + failed.join());
CompletableFuture<Integer> handle = CompletableFuture.<Integer>supplyAsync(() -> {
throw new IllegalStateException("bad");
}).handle((value, error) -> error == null ? value : -1);
System.out.println("handle: " + handle.join());
List<CompletableFuture<Integer>> tasks = List.of(
CompletableFuture.supplyAsync(() -> 10),
CompletableFuture.supplyAsync(() -> 20));
System.out.println("count: " + tasks.stream().map(CompletableFuture::join).toList());
}
}
javac -Xlint:all Futures.java
java Futures
thenApply: 40
thenCombine: Ada 36
allOf sum: 6
exceptionally: recovered: boom
handle: -1
count: [10, 20]
thenCombine
The second line joins two independent results, a name and an age, with a function of two arguments. The two tasks run at the same time and the function runs when both are there, which is the shape of a page that needs two services and shows one answer. The method that takes two values and returns nothing is thenAcceptBoth, and the one that takes two futures and ignores the second's value is thenCompose.
thenCompose is the one to know by name because it is not thenApply: a step whose function itself returns a future is flat, and thenApply of it would answer a future inside a future. The same distinction as map and flatMap of lesson 090, in the asynchronous form.
allOf
allOf takes any number of futures and answers one that is done when they are all done. It answers a CompletableFuture<Void>, so the values are read from the original futures after the join, which is what the program does to sum them. The companion is anyOf, which is done when the first one is, for the case where any answer will do.
A batch of independent calls is the case for allOf, and it is why the class exists in the form it does: the program states the batch, waits once and reads the results, instead of chaining a join per call and paying the time of the first before starting the second.
exceptionally and handle
A failure in a chain travels to the end of it, and join throws an CompletionException whose cause is the original. The two methods that turn a failure into a value are exceptionally, which runs only for a failure, and handle, which runs either way and gets the value or the error.
The two lines of the output are the two results: the first prints the message of the cause, which is why it reads recovered: boom and not recovered: java.lang.IllegalStateException. The second prints -1, because the handler decided that a failure is worth a value of its own. Both keep the chain going, which is the property a caller of a service wants.
What a CompletableFuture is
The default executor is the common ForkJoinPool, the same one the parallel streams of lesson 091 use, and a task that blocks its thread there slows every other one. An Executor can be passed to supplyAsync and to the other factories, and a service that calls a database should pass its own pool: the common pool has as many threads as the machine has cores, and a blocking task holds one of them.
The virtual threads of lesson 122 are the other answer to that: a blocking task on a virtual thread is cheap, so the pool is not the constraint. Either way, the chain in the source is a description of dependencies and not of threads, and a program that reads it sees which step waits for which.
Exercises
- Add a thenApply step to the thenCombine line that formats the two values.
- Replace allOf with three join calls and explain the difference in waiting.
- Make the thenApply step throw and catch the CompletionException of join.
- Pass an ExecutorService of one thread to supplyAsync and shut it down at the end.
Questions
A new set of questions in a new order every time. Choose one answer for each, then check.
-
What does
thenApplydo?Answer
Adds a step that transforms the value when it arrives
The step runs on the value the previous stage produced, and join waits at the end.
-
What does
allOfanswer?Answer
A future that is done when all of the given ones are done
It answers a Void future, and the values are read from the original futures.
-
What does
exceptionallydo?Answer
Runs a function of the error and answers its value when the chain failed
It is the recovery step, and handle is the one that runs on success as well.
-
What does this program print?
import java.util.concurrent.CompletableFuture; public class Q1 { public static void main(String[] args) { CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> 5); System.out.println(future.thenApply(n -> n + 1).thenApply(n -> n * 10).join()); } }Answer
60
Five plus one is six, and six times ten is sixty.
-
Why is
thenComposeneeded when the step returns a future?Answer
thenApply would answer a future of a future
It flattens the two levels, which is the difference between map and flatMap.
-
Which pool runs
supplyAsyncwhen none is given?Answer
The common ForkJoinPool of the process
The common pool is shared with the parallel streams, which is why a blocking task there is a problem.
-
What does
jointhrow when the chain failed?Answer
CompletionException with the original failure as its cause
The wrapper is unchecked, and the cause is the exception the task threw.
-
What does this program print?
import java.util.concurrent.CompletableFuture; public class Q2 { public static void main(String[] args) { CompletableFuture<String> a = CompletableFuture.supplyAsync(() -> "x"); CompletableFuture<String> b = CompletableFuture.supplyAsync(() -> "y"); System.out.println(a.thenCombine(b, String::concat).join()); System.out.println(a.isDone() + " " + b.isDone()); } }Answer
xy / true true
The combination waits for both, so both are done when the join returns.
-
What is the difference between
exceptionallyandhandle?Answer
handle runs on success and on failure, and exceptionally only on failure
handle receives both the value and the error, and exceptionally receives only the error.
-
What does a chain of thenApply steps describe?
Answer
The dependencies between the steps, and not the threads
The executor decides where a step runs, and the chain decides what waits for what.
The code on this page was built with OpenJDK 21.0.13 (javac and java) and run on Alpine Linux in a Docker container.
Article author: Arthur Isaev