How does CompletableFuture chain asynchronous work in Java, and why is it better than blocking on a Future?
A CompletableFuture is a promise of a value that you can chain more work onto, and the important part is that the chaining does not need a thread of its own.
With an ordinary Future, the only way to get the answer is to call the method get, and that call blocks until the work is done. If you call it on the thread that was going to do the work next, the whole thing stops until the answer arrives.
With a CompletableFuture, you attach the next step instead of waiting. The next step runs when the answer is ready, on whichever thread finished the work. So you can write a chain of steps and the thread that is free is the one that carries on.
import java.util.concurrent.CompletableFuture;
public class Main {
public static void main(String[] args) {
CompletableFuture<String> first = CompletableFuture.supplyAsync(() -> {
return "the first answer";
});
// The next step is attached, not waited for.
CompletableFuture<String> second = first.thenApply(text -> text + " and the second");
// Nothing has blocked. The chain is running in the background.
second.thenAccept(System.out::println);
second.join();
}
}
So why is it better than blocking on a future? Three reasons.
The first one is that the thread is not held while it waits. A thread that is blocked in the method get is doing nothing at all, and in a server with a fixed number of threads that is a thread that is not serving anybody.
The second one is that the chain is written as a chain. Each step says what happens next, and the reading goes from left to right in the order that the work happens.
The third one is that the failure handling is part of the chain, instead of being a try and catch wrapped around every step.
The next question in this topic looks at how to create one and how to chain it.