Sub topic 5
Chaining dependent calls with `thenCompose`
This chapter assumes you know Java 8 lambdas, generics, CompletableFuture, basic threads, and ExecutorService. It also assumes you have used supplyAsync and thenApply to start work and transform a result.
A dependent asynchronous call needs the result of an earlier call. For example, an application might load a user ID and then use that ID to load the user's profile. The second operation cannot start until the first one finishes.
thenCompose connects these operations into one CompletableFuture. It is useful when the function already returns a future.
The nested-future problem
Suppose loadUserId returns CompletableFuture<Integer>, and loadProfile accepts an ID and returns CompletableFuture<String>.
Using thenApply produces a nested future:
CompletableFuture<CompletableFuture<String>> nested =
loadUserId("alice").thenApply(id -> loadProfile(id));The outer future contains the inner future. You would need to unwrap both levels before using the profile.
thenCompose flattens the two levels:
CompletableFuture<String> profile =
loadUserId("alice").thenCompose(id -> loadProfile(id));The result has the useful type CompletableFuture<String>.
A complete dependent chain
The following program loads a user ID and then loads that user's profile. The join call is only used at the boundary of the program to obtain the final result.
import java.util.concurrent.CompletableFuture;
public class Chaining {
static CompletableFuture<Integer> loadUserId(String username) {
return CompletableFuture.supplyAsync(() -> {
System.out.println("Loading ID for " + username);
return username.length();
});
}
static CompletableFuture<String> loadProfile(int userId) {
return CompletableFuture.supplyAsync(() -> {
System.out.println("Loading profile for user " + userId);
return "profile-" + userId;
});
}
public static void main(String[] args) {
CompletableFuture<String> profile =
loadUserId("alice")
.thenCompose(Chaining::loadProfile);
System.out.println(profile.join());
}
}The method reference Chaining::loadProfile is equivalent to the lambda id -> loadProfile(id). When the first future completes normally, thenCompose passes its integer result to loadProfile. The returned future becomes the next stage in the chain.
The stages are dependent, so the profile operation cannot begin before the ID operation supplies its result.
Errors in a dependent chain
If the first operation fails, the function passed to thenCompose is not called. The combined future completes exceptionally.
If the first operation succeeds but loadProfile fails, the combined future also completes exceptionally. You can handle either failure after the chain:
CompletableFuture<String> profile = loadUserId("alice")
.thenCompose(Chaining::loadProfile)
.exceptionally(error -> "unavailable");A failure observed through join is commonly wrapped in CompletionException. Inspect its cause when your error handling needs the original exception.
Choosing the right operation
| Situation | Operation | Result type |
|---|---|---|
| Transform a value synchronously | `thenApply` | `CompletableFuture<R>` |
| Start another asynchronous operation | `thenCompose` | `CompletableFuture<R>` |
| Consume a value without returning one | `thenAccept` | `CompletableFuture<Void>` |
Do not use thenCompose merely because the work is asynchronous. Use it because the next function returns a future. If the next function calculates a plain string, thenApply is the correct operation.
Exercise
What is the type of the result when CompletableFuture<Integer> is followed by a function returning CompletableFuture<String>? Which method avoids a nested future?
Show answer
thenApply creates CompletableFuture<CompletableFuture<String>>, while thenCompose creates CompletableFuture<String> by flattening the dependent operation.