CompletableFuture
CompletableFuture is a result that may complete later. You can chain thenApply, thenCompose, and whenComplete, combine several futures, and complete it by hand. It is the composable successor to Future.
Detailed Explanation
Future.get() blocks and cannot be composed. CompletableFuture is both a Future and a completion API. supplyAsync runs a supplier on ForkJoinPool.commonPool() unless you pass an executor. thenApply maps the value when it arrives. thenCompose flats a future of a future. thenCombine waits for two. allOf waits for many and returns Void; you then join each. anyOf completes with the first result as Object.
Exceptions become the completion. join() throws CompletionException. get() throws ExecutionException. handle and whenComplete see both value and error. exceptionally recovers. An unchecked error in a callback completes the next stage exceptionally. Forgetting that is how pipelines die silently if nobody joins.
You can complete, completeExceptionally, or cancel. orTimeout (Java 9+) fails the future after a delay. Default async callbacks run on the common pool, which is a bad place for blocking I/O. Pass a dedicated Executor to *Async methods when the work blocks.
You reach for CompletableFuture when you have several I/O calls to overlap and then merge. You keep Future from ExecutorService.submit when you only get once. You keep reactive types when the stream is many values, not one.
The cost of supplyAsync on the common pool for blocking work is pool starvation: other parallel streams and futures pause. The cost of a chain that captures this is a retained object. The cost of get() on a future that depends on the current thread running the next stage is a deadlock. Prefer thenApply over a blocking get in a callback.
complete is ignored if the future is already done. obtrudeValue forces it and is for tests, not production.
Code Examples
import java.util.concurrent.CompletableFuture;
public class Map {
public static void main(String[] args) {
int n = CompletableFuture.supplyAsync(() -> "ada")
.thenApply(String::toUpperCase)
.thenApply(String::length)
.join();
System.out.println(n); // prints: 3
}
}import java.util.concurrent.CompletableFuture;
public class Both {
public static void main(String[] args) {
CompletableFuture<Integer> a = CompletableFuture.supplyAsync(() -> 2);
CompletableFuture<Integer> b = CompletableFuture.supplyAsync(() -> 3);
int sum = a.thenCombine(b, Integer::sum).join();
System.out.println(sum); // prints: 5
}
}Common Gotchas
Default executor is the common ForkJoinPool
do not block it. Pass your own executor for I/O.
Exceptions vanish until `join`/`get`/`whenComplete`
a failed stage looks fine if you ignore the future.
`allOf` does not return the values
keep the original futures and `join` them after.
`thenApply` vs `thenCompose`
compose when the function already returns a `CompletableFuture`.