The Problem thenCompose Solves: Avoiding Nested Futures
What you'll learn: Why using thenApply with functions that return CompletableFuture creates unwieldy nested structures, and how thenCompose elegantly solves this problem.
The Nested Future Problem
When you use thenApply to transform a result, it works beautifully if your transformation function returns a simple value. But what happens when your transformation itself is asynchronous—when it returns another CompletableFuture?
Here's the problem:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "user123");
// Suppose getUserDetails returns CompletableFuture<User>
CompletableFuture<CompletableFuture<User>> nested =
future.thenApply(userId -> getUserDetails(userId));
You end up with CompletableFuture<CompletableFuture<User>>—a future wrapped in a future! To get the actual User, you'd need to call get() twice or chain awkwardly. This nested structure breaks the clean pipeline pattern.
Why This Happens
thenApply simply wraps whatever your function returns inside a CompletableFuture. If your function already returns a CompletableFuture, you get double-wrapping.
Analogy: Imagine ordering a package (future), and when it arrives, inside is another package (another future). You have to open two boxes to get your item!
The Solution Preview
thenCompose is specifically designed to "flatten" this structure. When your transformation returns a CompletableFuture, thenCompose unwraps it automatically, giving you CompletableFuture<User> instead of the nested monstrosity.
Think of it as automatic unboxing—it removes one layer of wrapping so your pipeline stays clean and flat.
Key Takeaway: Use thenApply when your transformation returns a plain value; use thenCompose when your transformation returns a CompletableFuture to avoid nested CompletableFuture<CompletableFuture<T>> structures.