Sub topic 5
Chaining dependent calls with thenCompose
This chapter assumes you know Java 8 lambdas, Function and Supplier, ExecutorService, and the basics of supplyAsync and thenApply. It covers one operator, thenCompose. It explains why dependent asynchronous calls need it, how it behaves when something fails, and which mistakes come up most often.
The problem: a step that returns a future
thenApply takes a function from a value to a value. Many real steps are not like that. Looking up an order needs a user id, and the lookup is itself asynchronous, so it returns a CompletableFuture. If you pass that step to thenApply, the future ends up inside another future.
import java.util.concurrent.CompletableFuture;
public class Nested {
static CompletableFuture<Integer> fetchUserId(String name) {
return CompletableFuture.supplyAsync(() -> name.length());
}
static CompletableFuture<String> fetchOrder(int userId) {
return CompletableFuture.supplyAsync(() -> "order-" + userId);
}
public static void main(String[] args) {
CompletableFuture<CompletableFuture<String>> nested =
fetchUserId("alice").thenApply(id -> fetchOrder(id));
// Two joins are needed to reach the String.
String order = nested.join().join();
System.out.println(order);
}
}The type CompletableFuture<CompletableFuture<String>> is the warning sign. The outer future completes when fetchOrder has been started, not when the order is available. Anything you attach to the outer future runs too early, and you must unwrap the result by hand.
What thenCompose does
thenCompose takes a function from a value to a CompletionStage. It runs that function when the first stage completes. It then returns a future that completes when the inner stage completes, with the inner stage's result. The two layers become one.
The signature, simplified, is:
<U> CompletableFuture<U> thenCompose(Function<? super T, ? extends CompletionStage<U>> fn)The same example becomes flat:
import java.util.concurrent.CompletableFuture;
public class Flat {
static CompletableFuture<Integer> fetchUserId(String name) {
return CompletableFuture.supplyAsync(() -> name.length());
}
static CompletableFuture<String> fetchOrder(int userId) {
return CompletableFuture.supplyAsync(() -> "order-" + userId);
}
public static void main(String[] args) {
CompletableFuture<String> order =
fetchUserId("alice").thenCompose(id -> fetchOrder(id));
System.out.println(order.join());
}
}This prints order-5. The type is CompletableFuture<String>, and order completes only after both calls have finished.
The rule of thumb
- Use
thenApplywhen your function returns a plain value, such asStringorint. - Use
thenComposewhen your function returns aCompletableFutureor otherCompletionStage.
If the compiler shows you a nested CompletableFuture<CompletableFuture<...>>, you almost certainly wanted thenCompose. Programmers who know Stream will see the parallel. thenApply corresponds to map, and thenCompose corresponds to flatMap.
How the sequence runs
The diagram shows the order of events for fetchUserId(...).thenCompose(id -> fetchOrder(id)).
Two points follow from this order.
thenComposereturns at once. The function runs later, on whichever thread completes the first stage, unless you use anAsyncvariant.- The inner call starts only after the first stage succeeds. The two calls run in sequence by design, because the second needs the first one's output.
Chaining more than two steps
Dependent calls chain naturally. Each thenCompose flattens one level, so the type stays simple however long the chain is.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Pipeline {
record Order(int id, int userId) {}
static CompletableFuture<Integer> findUser(String name, ExecutorService ex) {
return CompletableFuture.supplyAsync(() -> name.length(), ex);
}
static CompletableFuture<Order> findLatestOrder(int userId, ExecutorService ex) {
return CompletableFuture.supplyAsync(() -> new Order(100 + userId, userId), ex);
}
static CompletableFuture<String> findShipment(Order order, ExecutorService ex) {
return CompletableFuture.supplyAsync(() -> "shipment for order " + order.id(), ex);
}
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(4);
try {
String result = findUser("alice", pool)
.thenCompose(id -> findLatestOrder(id, pool))
.thenCompose(order -> findShipment(order, pool))
.thenApply(String::toUpperCase)
.join();
System.out.println(result);
} finally {
pool.shutdown();
}
}
}This prints SHIPMENT FOR ORDER 105. The final thenApply is correct because toUpperCase returns a plain String. The example uses a record, so it needs Java 16 or later. On older versions, replace the record with a small class.
Passing the same executor into each helper keeps the work on a pool you control. The chapter on executors covers that choice in detail.
Keeping earlier values in scope
A common need is to use both the first result and the second result in a later step. A lambda can capture variables, so nest the later step inside the compose function.
import java.util.concurrent.CompletableFuture;
public class KeepBoth {
static CompletableFuture<Integer> fetchUserId(String name) {
return CompletableFuture.supplyAsync(() -> name.length());
}
static CompletableFuture<String> fetchOrder(int userId) {
return CompletableFuture.supplyAsync(() -> "order-" + userId);
}
public static void main(String[] args) {
String summary = fetchUserId("alice")
.thenCompose(id -> fetchOrder(id)
.thenApply(order -> "user " + id + " has " + order))
.join();
System.out.println(summary);
}
}This prints user 5 has order-5. The inner thenApply sits inside the lambda, so id is still visible. The result of the whole lambda is a CompletableFuture<String>, which thenCompose flattens. Keep this nesting shallow. Past two levels, move the inner part into a named method.
Errors in a composed chain
A failure can occur in three places, and each behaves slightly differently.
- The first stage fails. The function passed to
thenComposeis skipped, and the result future completes exceptionally with the same failure. - The function itself throws, for example because of a
NullPointerExceptionbefore it returns a future. The result future completes exceptionally with that exception. - The inner future fails. The result future completes exceptionally with the inner failure.
In every case the exception reaches the caller wrapped in a CompletionException when you call join. The following program shows the third case and recovers with exceptionally.
import java.util.concurrent.CompletableFuture;
public class ComposeErrors {
static CompletableFuture<Integer> fetchUserId(String name) {
return CompletableFuture.supplyAsync(() -> name.length());
}
static CompletableFuture<String> fetchOrder(int userId) {
return CompletableFuture.supplyAsync(() -> {
if (userId > 3) {
throw new IllegalStateException("no orders for user " + userId);
}
return "order-" + userId;
});
}
public static void main(String[] args) {
String result = fetchUserId("alice")
.thenCompose(ComposeErrors::fetchOrder)
.exceptionally(ex -> {
System.out.println("caught: " + ex);
return "no-order";
})
.join();
System.out.println(result);
}
}The handler prints caught: java.util.concurrent.CompletionException: java.lang.IllegalStateException: no orders for user 5, and the program then prints no-order. Because exceptionally sits after thenCompose, it covers a failure in either call. If you want to recover from the first call only, place the handler before thenCompose. That keeps a failure of the first call from skipping the second step. Where you put the handler decides which steps it protects.
A subtle point about exception wrapping
When the inner future fails, the exception that arrives at the later handler is typically a CompletionException whose cause is the original exception. Do not assume the argument to exceptionally is your own exception type. To inspect the real cause, unwrap it:
Throwable cause = (ex instanceof java.util.concurrent.CompletionException && ex.getCause() != null)
? ex.getCause()
: ex;The wrapping rules have exceptions, and the chapter on error handling covers them fully. A defensive unwrap like the one above is safe in both cases.
Using a dependent call that is not async
thenCompose accepts any CompletionStage, including one that is already complete. That makes it easy to mix asynchronous steps with cheap synchronous ones, for example a cache check.
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
public class CachedLookup {
static final Map<Integer, String> CACHE = new ConcurrentHashMap<>();
static CompletableFuture<String> loadFromRemote(int id) {
return CompletableFuture.supplyAsync(() -> "value-" + id)
.thenApply(v -> {
CACHE.put(id, v);
return v;
});
}
static CompletableFuture<String> lookup(int id) {
String cached = CACHE.get(id);
if (cached != null) {
return CompletableFuture.completedFuture(cached);
}
return loadFromRemote(id);
}
public static void main(String[] args) {
System.out.println(CompletableFuture.completedFuture(7).thenCompose(CachedLookup::lookup).join());
System.out.println(CompletableFuture.completedFuture(7).thenCompose(CachedLookup::lookup).join());
}
}Both lines print value-7. The first call goes to the loader, and the second is served from the cache. Both paths return a CompletableFuture<String>, so the caller treats them the same way. This is a main reason to design methods that return futures: callers do not need to know whether the answer was computed or remembered.
Edge cases and gotchas
| Situation | What happens | What to do |
|---|---|---|
| Function passed to `thenCompose` returns `null` | The result future fails with a `NullPointerException` | Return `CompletableFuture.completedFuture(null)` when you mean "no value" |
| Using `thenApply` where `thenCompose` is needed | You get a nested future, and later stages run before the inner work finishes | Change to `thenCompose` |
| Using `thenCompose` where `thenApply` is needed | Compile error, because a plain value is not a `CompletionStage` | Change to `thenApply` |
| Blocking with `join` inside the compose function | The thread that runs the function is held until the inner future finishes | Return the inner future instead of joining it |
| Two independent calls chained with `thenCompose` | They run one after the other and take the sum of both times | Start both first, then merge with `thenCombine` |
The last two rows are the most costly in practice. Consider this code:
// Wrong: blocks a pool thread and hides the dependency chain
fetchUserId("alice").thenApply(id -> fetchOrder(id).join());It compiles and returns the right type, but it occupies a thread for the whole inner call. On the common pool, which is small, a few of these can starve all other asynchronous work. Writing thenCompose(id -> fetchOrder(id)) frees the thread, because the inner future completes the result without anyone waiting on it.
The independent-calls case needs a different shape. If fetchPrice does not need the order, do not put it after the order in a chain.
CompletableFuture<String> order = fetchOrder(5);
CompletableFuture<Integer> price = fetchPrice(5); // both already running
CompletableFuture<String> both = order.thenCombine(price, (o, p) -> o + " costs " + p);thenCompose expresses "B needs A's result". thenCombine expresses "A and B are separate, and I need both".
Which thread runs the function
thenCompose has the same three forms as the other stage methods:
thenCompose(fn)runsfnon the thread that completed the earlier stage, or on the calling thread if that stage is already complete when you call it.thenComposeAsync(fn)runsfnon the common pool.thenComposeAsync(fn, executor)runsfnon the executor you give it.
The function only creates the inner future. It normally does little work itself, so the plain form is usually right. Use an Async form when fn does non-trivial setup before returning the future, or when you must not run on the completing thread, for example a thread that belongs to an event loop. Passing an executor to thenComposeAsync affects only the compose function. It does not move the inner future's own work, which runs wherever you started it.
Summary of the working model
- A step that returns a future needs
thenCompose, notthenApply. - The result future completes after the inner future does, and it carries the inner value or failure.
- Steps in a
thenComposechain run in sequence. UsethenCombinefor independent work. - A failure anywhere skips later success stages, and one handler placed after the chain covers every step before it.
- Never call
joinorgetinside a compose function.
Exercise
A teammate writes fetchUserId("bob").thenApply(id -> fetchOrder(id)).thenApply(order -> "Got " + order).join(), where fetchOrder returns CompletableFuture<String>. What does it print, and how do you fix it?
Show answer
It prints something like Got java.util.concurrent.CompletableFuture@1b2c3d[Not completed] (the exact text varies). The first thenApply returns a CompletableFuture<CompletableFuture<String>>, so the next stage receives the inner future object, not its String result. Replace the first thenApply with thenCompose(id -> fetchOrder(id)). The second stage then receives the order string and the program prints Got order-3.
Exercise
You need loadProfile(id) and loadSettings(id), which both depend only on id, and then a render(profile, settings) step that returns a plain String. Should you chain the two loads with thenCompose? Describe the better shape.
Show answer
No. Chaining them with thenCompose runs them one after the other, even though neither needs the other's result. Start both futures first, for example var p = loadProfile(id); var s = loadSettings(id);, then call p.thenCombine(s, (profile, settings) -> render(profile, settings)). Both loads run at the same time, and the total time is about the slower of the two.