Sub topic 13
Composing Asynchronous Work with CompletableFuture
In earlier chapters you used Future to get a result back from a task. A Future has one weakness. To use its value, you must call get(), and get() makes your thread wait. A CompletableFuture removes that wait. It lets you say "when this result is ready, do this next step," and it keeps going without blocking.
What Is CompletableFuture?
A CompletableFuture is a Future that can run follow-up steps on its own when its result arrives. Each step returns a new CompletableFuture, so you can link steps into a chain. This is called composing asynchronous work. Asynchronous means the work runs in the background while your code moves on.
Here are the methods you will use most:
| Method | What it does |
|---|---|
| `supplyAsync(supplier, executor)` | Starts a task that returns a value, on the executor you choose |
| `thenApply(function)` | Changes the result into a new value |
| `thenAccept(consumer)` | Uses the result but returns nothing |
| `exceptionally(function)` | Gives a fallback value if an earlier step failed |
| `join()` | Waits for the final value and returns it |
A Worked Example
This program starts with the number 21, doubles it, and turns it into a message.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CompletableFutureDemo {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
CompletableFuture<String> result = CompletableFuture
.supplyAsync(() -> 21, pool)
.thenApply(n -> n * 2)
.thenApply(n -> "Answer: " + n);
System.out.println(result.join());
} finally {
pool.shutdown();
}
}
}Here is what happens, step by step:
supplyAsync(() -> 21, pool)runs the lambda on a thread frompool. It returns aCompletableFuture<Integer>.- The first
thenApplywaits for 21 and turns it into 42. - The second
thenApplyturns 42 into the text"Answer: 42". join()waits for the last step and printsAnswer: 42.- The
finallyblock shuts the pool down, as you learned in the shutdown chapter.
Handling Failure in a Chain
In the previous chapter, a failed task's exception came back wrapped inside an ExecutionException from Future.get(). A CompletableFuture chain gives you another option. If any step throws, the steps after it are skipped. The exception then travels down to exceptionally, which can return a fallback value.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class FallbackDemo {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
int value = CompletableFuture
.supplyAsync(() -> Integer.parseInt("oops"), pool)
.thenApply(n -> n * 2)
.exceptionally(ex -> {
System.out.println("Failed: " + ex.getCause());
return -1;
})
.join();
System.out.println("Value: " + value);
} finally {
pool.shutdown();
}
}
}The text "oops" is not a number, so parseInt throws a NumberFormatException. The thenApply step never runs. exceptionally prints the error and returns -1, so the program prints Value: -1.
Exercise
In the first example, what would the program print if you added .thenApply(s -> s + "!") right after the second thenApply?
Show answer
It would print Answer: 42!. The new step receives the text "Answer: 42" and adds an exclamation mark before join() returns it.
Exercise
Why is it a good idea to pass pool as the second argument to supplyAsync?
Show answer
It makes the task run on a pool you control and shut down yourself. Without it, the task runs on the shared common pool, where slow tasks can hold up other work in the program.