Advanced 12 min
Combining asynchronous results
A CompletableFuture represents a value that may become available later.
How it works
Follow the shape of the result. A transformation from a price to a string can use thenApply because it returns the string immediately. A lookup that returns another future can use thenCompose, giving later code a future for the lookup’s final answer.
Walk through an example
Use thenApply when you can transform a completed result immediately. Use thenCompose when the next operation itself returns a future and you want a single future for its eventual value.
What to watch for
Handle an exceptional result deliberately. When you join, failures can arrive wrapped in a CompletionException.
Code example
public class Main {
public static void main(String[] args) {
var answer = java.util.concurrent.CompletableFuture.completedFuture(5)
.thenApply(value -> value * 2);
System.out.println(answer.join());
}
}Check your understanding
What value does the transformed future hold?
See the example and explanation
- Worked example
- Given
A completed future holds 5 and thenApply doubles it. - Answer
10
The transformation receives 5 after completion and returns 10 as the next result.