CompletableFuture
A Future that can be completed later and chained, letting you describe asynchronous steps such as transform, combine and recover without nesting callbacks.
In more detail
Methods such as thenApply and thenCombine return new futures, so each step is an immutable description of work that runs when its input is ready. A failure skips the later success steps until exceptionally or a final handler deals with it. join and get still block, so call them only at a boundary where waiting is safe. Choose an executor explicitly for blocking work instead of the common pool.
Example
CompletableFuture.supplyAsync(() -> "ready").thenApply(String::toUpperCase).join()Related terms
- supplyAsync — The CompletableFuture method that starts a task producing a value on another thread and returns a future for it.
- thenApply — The CompletableFuture method that transforms a stage's result once it is available, producing a new stage.
- thenCombine — The CompletableFuture method that waits for two independent stages and combines their results with a function.
- exceptionally — The CompletableFuture method that supplies a fallback result when an earlier stage has failed.
- CompletionException — The unchecked exception CompletableFuture.join throws when the future failed, wrapping the real cause.
- Future — An object representing the result of a task that may not have finished yet; get waits for it.
- asynchronous — Describes work that starts now and finishes later, letting the program do other things instead of waiting for it.
Taught in
- The ExecutorService — Modern Java: Virtual Threads & High-Throughput Services
- Async With CompletableFuture — Modern Java: Virtual Threads & High-Throughput Services