Video in progress
In CompletableFuture, how do thenApply, thenCompose and thenCombine differ?
thenApply transforms the result with a plain function. thenCompose is used when the next step itself returns a CompletableFuture, and it "flattens" the nested future. thenCombine merges the results of two independent futures.
📖 Answer
It is easy to compare them to map and flatMap in streams:
CompletableFuture<User> userF = userClient.findAsync(id);
// thenApply: a synchronous transformation (map)
CompletableFuture<String> nameF = userF.thenApply(User::fullName);
// thenCompose: the next step is async too (flatMap)
CompletableFuture<List<Order>> ordersF =
userF.thenCompose(u -> orderClient.findByUserAsync(u.id()));
// written with thenApply, the type gets awkward:
// CompletableFuture<CompletableFuture<List<Order>>>
// thenCombine: two parallel requests
CompletableFuture<Profile> profileF = userF.thenCombine(
balanceClient.getAsync(id),
(user, balance) -> new Profile(user, balance));
With thenCombine, both requests go out at the same time. With sequential thenCompose the total time adds up, while here you pay only for the longest one. For more than two futures there is CompletableFuture.allOf(...), and then you take each result with join().
The variants with the Async suffix (thenApplyAsync) run the step on another thread. If you don't pass an executor, ForkJoinPool.commonPool() is used, so for blocking I/O give it your own executor.
Sign up to mark studied questions and save your progress.