CompletableFuture chaining: thenApply/thenCompose/thenCombine, sync vs. async
thenApply transforms a result. thenCompose chains to another async operation (like flatMap for
futures -- use this, not thenApply, when your transform itself returns a CompletableFuture, or you'll
end up with a future-of-a-future). thenCombine merges two independent futures. The ...Async variant of
each guarantees execution on the common pool; the plain variant may run on the completing thread if the
future is already done by the time you attach the callback.
import java.util.concurrent.*;
CompletableFuture<Integer> f1 = CompletableFuture.supplyAsync(() -> 21).thenApply(x -> x * 2);
System.out.println("thenApply: " + f1.get());
CompletableFuture<Integer> f2 = CompletableFuture.supplyAsync(() -> 5)
.thenCompose(x -> CompletableFuture.supplyAsync(() -> x * x));
System.out.println("thenCompose (chains to another future): " + f2.get());
CompletableFuture<Integer> a = CompletableFuture.supplyAsync(() -> 3);
CompletableFuture<Integer> b = CompletableFuture.supplyAsync(() -> 4);
System.out.println("thenCombine (merges two independent futures): " + a.thenCombine(b, (x, y) -> x + y).get());
The sync/async distinction, made visible by printing which thread each callback actually runs on:
String mainThreadName = Thread.currentThread().getName();
CompletableFuture<Void> chain = CompletableFuture.supplyAsync(() -> "value")
.thenApply(v -> {
System.out.println(" thenApply runs on: " + Thread.currentThread().getName());
return v;
})
.thenApplyAsync(v -> {
System.out.println(" thenApplyAsync runs on: " + Thread.currentThread().getName() + " (always a pool thread)");
return v;
})
.thenAccept(v -> {});
chain.get();
exceptionally recovers from a failed future, without needing a try/catch around a blocking .get():
CompletableFuture<Integer> failing = CompletableFuture.<Integer>supplyAsync(() -> {
throw new RuntimeException("computation failed");
}).exceptionally(ex -> {
System.out.println(" recovered from: " + ex.getMessage());
return -1;
});
System.out.println("recovered value: " + failing.get());