Sub topic 2
Chaining Asynchronous Work with `CompletableFuture`
Assume Java 8 lambdas, generics, and basic ExecutorService use. A CompletableFuture<T> represents a result that may be available later.
Chaining dependent calls with `thenCompose`
Use thenCompose when the next asynchronous operation needs the previous result. It flattens two stages into one CompletableFuture, avoiding a nested type such as CompletableFuture<CompletableFuture<String>>.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class ComposeDemo {
static CompletableFuture<Integer> findUserId(String name, ExecutorService pool) {
return CompletableFuture.supplyAsync(name::length, pool);
}
static CompletableFuture<String> findOrder(int id, ExecutorService pool) {
return CompletableFuture.supplyAsync(() -> "order-" + id, pool);
}
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
String order = findUserId("alice", pool)
.thenCompose(id -> findOrder(id, pool))
.join();
System.out.println(order);
} finally {
pool.shutdown();
}
}
}The second call starts only after the user ID is available.
Combining independent results with `thenCombine`
Use thenCombine when two futures can run independently. Its combining function receives both completed values.
CompletableFuture<String> order =
CompletableFuture.supplyAsync(() -> "order-5");
CompletableFuture<Integer> price =
CompletableFuture.supplyAsync(() -> 42);
String summary = order
.thenCombine(price, (name, amount) -> name + " costs " + amount)
.join();Running many tasks with `allOf` and `anyOf`
allOf completes after every input future completes, but its result type is Void. Collect individual results afterward. anyOf completes when the first future completes and returns a future of Object, so cast or convert the result carefully.
flowchart TD
A[Start independent tasks] --> B{Wait strategy}
B -->|allOf| C[Wait for every task]
B -->|anyOf| D[Use the first completed task]Handling errors
Use exceptionally to replace a failure with a fallback. Use handle when you need both the value and the exception. Use whenComplete for logging or metrics; it observes the outcome without normally changing it.
CompletableFuture<Integer> result =
CompletableFuture.supplyAsync(() -> Integer.parseInt("bad"))
.handle((value, error) -> error == null ? value : -1);
System.out.println(result.join()); // -1join() reports failure by throwing CompletionException, whose cause is the original exception. get() reports checked exceptions instead. Handle failures at the stage where you can make a meaningful decision.
Exercise
Which method should you use when a second asynchronous call depends on the first call's result?
Show answer
Use thenCompose, because it flattens the dependent future into one future.