thenCompose versus thenApply
35 min · Advanced
Need help? Ask a tutor on WhatsApp (opens in a new tab)Real services are often async themselves: findUser(id) already returns a CompletableFuture<User>. To chain such a method you need thenCompose, not thenApply, or you end up with a future inside a future.
Nested CompletableFuture<CompletableFuture<T>>
A nested future is a CompletableFuture<CompletableFuture<T>>: a box inside a box. You get one when the function you pass to thenApply itself returns a CompletableFuture.
Example 1 · thenApply with an async method gives a box in a box
import java.util.List;import java.util.concurrent.CompletableFuture;
record User(int id, String name) {}
public class NestedFutureDemo { static CompletableFuture<User> findUser(int id) { return CompletableFuture.supplyAsync(() -> new User(id, "Riya")); }
static CompletableFuture<List<String>> fetchOrders(User user) { return CompletableFuture.supplyAsync(() -> List.of("Keyboard", "Mouse")); }
public static void main(String[] args) { CompletableFuture<CompletableFuture<List<String>>> nested = findUser(7).thenApply(user -> fetchOrders(user));
Object outerValue = nested.join(); System.out.println("join() gave a " + outerValue.getClass().getSimpleName()); System.out.println("join().join() gave " + nested.join().join()); }}join() gave a CompletableFuture join().join() gave [Keyboard, Mouse]
What this code does
fetchOrdersreturns a future, andthenApplywraps it in another future. The type spells it out:CompletableFuture<CompletableFuture<List<String>>>.- The first
join()gives the inner future, not the orders. Only a secondjoin()reaches the list, and any furtherthenApplywould have to deal with the inner future too.
thenApply wraps whatever the function returns. If the function returns a List, you get a future of a List. If it returns a future of a List, you get a future of a future of a List. To reach the value you would need join().join(), and the next thenApply would receive a future instead of the orders. Writing CompletableFuture<List<String>> orders = findUser(7).thenApply(u -> fetchOrders(u)); fails with incompatible types: inference variable U has incompatible bounds.
Fix the error
Pick the method that compiles
Read the real compiler error, then pick the line that fixes it.
Round 1 of 2
fetchOrders returns a future, and the result must be a flat future of the list.
Error
NestedFix.java:11: error: incompatible types: inference variable U has incompatible bounds
CompletableFuture<List<String>> orders = findUser(7).thenApply(u -> fetchOrders(u));
equality constraints: List<String>
lower bounds: CompletableFuture<List<String>>thenCompose flattens like flatMap
thenCompose is a CompletableFuture method for a function that itself returns a future. It chains the two calls and returns one flat CompletableFuture, the way flatMap flattens nested containers.
thenCompose(fn) takes a function that returns a CompletableFuture<U> and gives back a flat CompletableFuture<U>. It is the flatMap of CompletableFuture, just like Optional.flatMap and Stream.flatMap.
// map wraps the result, flatMap does not wrap it a second timeOptional<Optional<Address>> a = user.map(User::address); // address() returns OptionalOptional<Address> b = user.flatMap(User::address);
CompletableFuture<CompletableFuture<List<String>>> c = findUser(7).thenApply(u -> fetchOrders(u));CompletableFuture<List<String>> d = findUser(7).thenCompose(u -> fetchOrders(u));The rule is short: if the function returns a plain value, use thenApply; if it returns a future, use thenCompose. The future from thenCompose completes when the inner future completes, with the inner future's value.
Example 2 · thenCompose gives a flat future
import java.util.List;import java.util.concurrent.CompletableFuture;
record User(int id, String name) {}
public class ThenComposeDemo { static CompletableFuture<User> findUser(int id) { return CompletableFuture.supplyAsync(() -> new User(id, "Riya")); }
static CompletableFuture<List<String>> fetchOrders(User user) { return CompletableFuture.supplyAsync(() -> List.of("Keyboard", "Mouse")); }
public static void main(String[] args) { CompletableFuture<List<String>> orders = findUser(7).thenCompose(user -> fetchOrders(user));
CompletableFuture<Integer> count = orders.thenApply(list -> list.size()); System.out.println("Orders: " + orders.join()); System.out.println("Count: " + count.join()); }}Orders: [Keyboard, Mouse] Count: 2
What this code does
- Same two methods, one word changed.
thenComposereturnsCompletableFuture<List<String>>, so onejoin()gives the list. - Because the future is flat, the next step
thenApply(list -> list.size())receives the real list and can callsize()on it.
Dependent calls: find user, then fetch orders
A dependent call is a call that needs the result of an earlier call as its input. You cannot fetch Riya's orders before you know Riya's user id, so the two calls must run one after the other.
Example 3 · Three dependent calls: token, user, orders
import java.util.List;import java.util.concurrent.CompletableFuture;
record User(int id, String name) {}
record Order(String item, int price) {}
public class DependentCallsDemo { static CompletableFuture<Integer> userIdForToken(String token) { return CompletableFuture.supplyAsync(() -> { System.out.println("Looking up session token " + token); return 7; }); }
static CompletableFuture<User> findUser(int id) { return CompletableFuture.supplyAsync(() -> { System.out.println("Found user Riya (id " + id + ")"); return new User(id, "Riya"); }); }
static CompletableFuture<List<Order>> fetchOrders(User user) { return CompletableFuture.supplyAsync(() -> { System.out.println("Fetching orders of " + user.name()); return List.of(new Order("Keyboard", 320), new Order("Mouse", 120), new Order("Headset", 200)); }); }
public static void main(String[] args) { CompletableFuture<String> summary = userIdForToken("abc123") .thenCompose(id -> findUser(id)) .thenCompose(user -> fetchOrders(user)) .thenApply(orders -> "Riya has " + orders.size() + " orders, total Rs " + orders.stream().mapToInt(Order::price).sum());
System.out.println(summary.join()); }}Looking up session token abc123 Found user Riya (id 7) Fetching orders of Riya Riya has 3 orders, total Rs 640
What this code does
- Each service needs the previous answer: the id needs the token, the user needs the id, the orders need the user.
thenComposestarts each call only when its input is ready, so the log lines always come in this order. - The last step builds a plain
String, so it is athenApply. The summary is the only valuemainwaits for.
thenCompose says exactly that: "when the user arrives, start the order call with it". No thread sits blocked in between; the second call simply starts when the first one finishes. When calls do not depend on each other, running them one after the other wastes time. The next lesson shows how to run independent calls side by side.
Reading long chains
A long chain is easy to read when you know the type after each step. Write one call per line and, while learning, add the type as a comment.
Example 4 · A long chain, with the type after each step
import java.util.concurrent.CompletableFuture;
record Passenger(String pnr, String name, String train) {}
public class LongChainDemo { static CompletableFuture<Passenger> findPassenger(String pnr) { return CompletableFuture.supplyAsync(() -> new Passenger(pnr, "meera iyer", "12627")); }
static CompletableFuture<String> seatFor(String train, String pnr) { return CompletableFuture.supplyAsync(() -> "B2-41"); }
public static void main(String[] args) { CompletableFuture<String> sms = CompletableFuture .supplyAsync(() -> " 4521897630 ") .thenApply(String::trim) // CF<String> plain value -> thenApply .thenCompose(pnr -> findPassenger(pnr)) // CF<Passenger> returns a future -> thenCompose .thenCompose(p -> seatFor(p.train(), p.pnr()) // CF<String> needs p and the seat .thenApply(seat -> p.name().toUpperCase() + ", train " + p.train() + ", seat " + seat)) .thenApply(text -> "SMS: " + text);
System.out.println(sms.join()); }}SMS: MEERA IYER, train 12627, seat B2-41
What this code does
- Read down the comments: they say what the future holds after a step, and why it is
thenApplyorthenCompose. The first and the last steps also hold aCompletableFuture<String>. - The message needs both the passenger
pand theseat. The innerthenApplysits inside thethenComposelambda, wherepis still in scope.
Example 5 · completedFuture when the answer is already known
import java.util.HashMap;import java.util.Map;import java.util.concurrent.CompletableFuture;
public class CachedLookupDemo { static Map<Integer, String> cache = new HashMap<>();
static CompletableFuture<String> nameOf(int roll) { String hit = cache.get(roll); if (hit != null) { return CompletableFuture.completedFuture(hit); // no thread needed } return CompletableFuture.supplyAsync(() -> { System.out.println(" server call for roll " + roll); return "Student-" + roll; }); }
public static void main(String[] args) { cache.put(1, "Aarav");
for (int roll : new int[] {1, 2}) { String line = CompletableFuture.supplyAsync(() -> roll) .thenCompose(r -> nameOf(r)) .thenApply(name -> "Roll " + roll + ": " + name) .join(); System.out.println(line); } }}Roll 1: Aarav server call for roll 2 Roll 2: Student-2
What this code does
nameOfalways returns a future, so it always fitsthenCompose. For a cache hit it returnscompletedFuture(hit), which is already done and costs no thread.- Only roll 2 misses the cache, so only roll 2 makes a server call. The caller's chain is the same for both cases.
- Function returns a plain value (
String::trim,total * 118 / 100) →thenApply. - Function returns a future (
findUser,fetchOrders) →thenCompose. - Value already known →
CompletableFuture.completedFuture(value). - Never
join()inside a step: it blocks a pool thread; usethenComposeinstead.
Two patterns come up often. When a later step needs a value from an earlier one, nest a thenApply inside the thenCompose lambda so both are in scope. When a method sometimes already has the answer, for example from a cache, it returns CompletableFuture.completedFuture(value), so callers still get a future.
Next step
Check your understanding
11 quick questions