Building dependency graphs
Definition:
A CompletionStage graph expresses which asynchronous outcomes depend on others.
Explanation:
thenApply is a synchronous transformation of a successful value, thenCompose flattens a dependent stage, and thenCombine joins independent successful stages.
Illustration image:
Example:
var user = java.util.concurrent.CompletableFuture.supplyAsync(api::loadUser, ioPool);
var order = user.thenCompose(u -> api.loadOrderAsync(u.id()));
return order.thenApply(Order::status);Expected behavior. The order call begins after the user ID exists and the result remains a single completion stage.
Internal working:
A non-Async continuation may execute on the thread completing its parent. Keep expensive or blocking continuations away from request threads and event loops unless the execution placement is intentional.
Interview questions:
When should thenCompose replace thenApply?
Use thenCompose when the callback returns a stage and the caller needs its eventual result without nested stages.