CompletableFuture: Future grows up
Plain Future could only block. CompletableFuture let you say what happens next.
Open this lesson in the learning hubKey points
Future.get()blocks - so "run in the background" ended with the caller waiting anyway.- You could not combine two Futures, react to failure, or chain a next step without a thread parked on each.
CompletableFutureadds callbacks:thenApply,thenCompose,thenCombine.- Failure travels down the chain and is caught by
exceptionallyorhandle. - Async variants default to the common ForkJoinPool - pass your own executor for blocking I/O.
Example
import java.util.concurrent.*;
public class Main {
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
CompletableFuture<String> user =
CompletableFuture.supplyAsync(() -> "ada", pool);
CompletableFuture<Integer> orders =
CompletableFuture.supplyAsync(() -> 3, pool);
// Combine two independent results without blocking on either
String summary = user.thenCombine(orders, (u, n) -> u + " has " + n + " orders").get();
System.out.println(summary);
// Failure flows down the chain
String recovered = CompletableFuture
.<String>supplyAsync(() -> { throw new IllegalStateException("db down"); }, pool)
.exceptionally(ex -> "recovered from: " + ex.getCause().getMessage())
.get();
System.out.println(recovered);
} finally {
pool.shutdown();
pool.awaitTermination(2, TimeUnit.SECONDS);
}
}
}
CompletableFuture replaced "wait for the answer" with "tell me what to do when it arrives".
This is a reading copy. The full lesson — with the visual explainer, the interactive lab and a Run button for the code — lives in the Java 8 Course course, and every lesson in it is listed on the Java 8 Course contents page.