CompletableFuture in Java 8
CompletableFuture is a Future that you can chain, combine and complete. Introduced in Java 8 as part of JEP 155, it lets you describe asynchronous work as a pipeline of steps instead of blocking a thread while you wait.
This tutorial covers starting async tasks, chaining and combining results, waiting for many tasks, and handling errors.
1. Why Was CompletableFuture Added?
A plain Future from an ExecutorService offers only get(), which blocks. You cannot say "when this finishes, do that", combine two futures, or handle an error without blocking a thread. CompletableFuture adds callbacks for all of these, which makes it practical to run independent remote calls in parallel and merge their results.
2. Key Methods
| Method | What it does |
|---|---|
supplyAsync(supplier[, executor]) | runs a task that returns a value |
thenApply(fn) | transforms the result |
thenCompose(fn) | chains another async step that returns a CompletableFuture |
thenCombine(other, fn) | combines two independent results |
allOf(...) / anyOf(...) | waits for all / the first of many futures |
exceptionally(fn) | replaces a failure with a fallback value |
handle(fn) | receives either the result or the exception |
join() | waits and returns the result (unchecked exceptions) |
3. Practical Examples
Example 1: Two calls in parallel, combined
The price and the tax rate are fetched at the same time on a two-thread pool, so the total wait is about the longer of the two calls, not their sum.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class AsyncPipeline {
static int fetchPrice(String item) {
sleep(200); // pretend this is a remote call
return item.equals("laptop") ? 55000 : 1200;
}
static double fetchTaxRate() {
sleep(150);
return 0.18;
}
static void sleep(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { Thread.currentThread().interrupt(); }
}
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
// Two independent calls run at the same time
CompletableFuture<Integer> price = CompletableFuture.supplyAsync(() -> fetchPrice("laptop"), pool);
CompletableFuture<Double> tax = CompletableFuture.supplyAsync(AsyncPipeline::fetchTaxRate, pool);
// thenCombine waits for both; thenApply transforms the result
CompletableFuture<String> invoice = price
.thenCombine(tax, (p, t) -> p * (1 + t))
.thenApply(total -> String.format("Total with tax: %.2f", total));
System.out.println(invoice.join()); // join() waits for the result
pool.shutdown();
}
}
Total with tax: 64900.00
Example 2: Many tasks and error handling
Each SKU lookup runs asynchronously. exceptionally turns a failed lookup into a readable value, allOf waits for every task, and handle shows the alternative that sees both outcomes.
import java.util.Arrays;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.stream.Collectors;
public class ErrorsAndAllOf {
static String loadStock(String sku) {
if (sku.startsWith("X")) {
throw new IllegalStateException("unknown SKU " + sku);
}
return sku + "=in stock";
}
public static void main(String[] args) {
List<String> skus = Arrays.asList("A100", "X999", "B200");
// One future per SKU; exceptionally() turns a failure into a fallback value
List<CompletableFuture<String>> futures = skus.stream()
.map(sku -> CompletableFuture.supplyAsync(() -> loadStock(sku))
.exceptionally(ex -> sku + "=error (" + ex.getCause().getMessage() + ")"))
.collect(Collectors.toList());
// allOf completes when every future has completed
CompletableFuture.allOf(futures.toArray(new CompletableFuture<?>[0])).join();
futures.stream().map(CompletableFuture::join).forEach(System.out::println);
// handle() sees either the result or the exception
String status = CompletableFuture.supplyAsync(() -> loadStock("X1"))
.handle((value, ex) -> ex == null ? value : "handled: " + ex.getCause().getClass().getSimpleName())
.join();
System.out.println(status);
}
}
A100=in stock X999=error (unknown SKU X999) B200=in stock handled: IllegalStateException
The exception passed to these callbacks is a CompletionException that wraps the original one, which is why the example calls getCause().
4. How the Pipeline Runs
5. Important Points and Best Practices
- Without an executor argument, async methods use the shared
ForkJoinPool.commonPool(). Pass your own executor for blocking I/O. - Always end a chain with error handling (
exceptionallyorhandle), or failures may go unnoticed. - Use
thenCompose, notthenApply, when the next step itself returns aCompletableFuture. - Prefer
join()in streams because it throws unchecked exceptions;get()throws checked ones. - Shut down executors you create, as the example does.
6. Summary
CompletableFuturewas added in Java 8 (JEP 155) for composable async code.- Start tasks with
supplyAsync; chain withthenApplyandthenCompose. - Combine results with
thenCombineandallOf. - Handle failures with
exceptionallyorhandle.
Related Tutorials
- CompletableFuture Class in Java
- Executor Framework in Java
- Virtual Threads (Java 21)
- Multithreading in Java
7. References
Frequently Asked Questions (FAQ)
Q1. What is the difference between Future and CompletableFuture?
A Future can only be checked or waited on with get(). A CompletableFuture also supports callbacks, chaining, combining several futures, manual completion and error handling.
Q2. What is the difference between thenApply and thenCompose?
thenApply maps the result with a normal function. thenCompose is used when the function itself returns a CompletableFuture, so the result is flattened instead of nested.
Q3. Which thread pool does supplyAsync use?
By default the common ForkJoinPool. An overload accepts an Executor, which is recommended for blocking tasks.
Q4. What is the difference between join() and get()?
Both wait for the result. get() throws checked InterruptedException and ExecutionException; join() throws the unchecked CompletionException.