Compose Asynchronous Pipelines with Java CompletableFuture
Build non-blocking async pipelines in Java using CompletableFuture with thenCompose, thenCombine, allOf, anyOf, exception handling, timeouts, and custom thread pools.
Overview
CompletableFuture is Java’s composable async primitive: thenCompose sequences dependent calls, thenCombine and allOf fan work out in parallel, and exceptionally, handle and whenComplete cover the error paths without try/catch noise. This recipe builds a small API aggregation pipeline — fetch a user, fetch their orders, merge the results — and then goes through the details that matter in production: custom executors, timeouts, retries with real delays, and the failure semantics of allOf that most tutorials skip.
When to Use This
- Aggregating responses from several services into one view (dashboard, profile, report endpoints)
- Multi-step async pipelines: fetch → transform → persist
- Racing the same call against replicas and keeping the first answer
- Replacing nested callbacks or
Future.get()chains with composable stages
If the workload is mostly blocking I/O inside a thread-per-request model, virtual threads are usually the simpler answer. CompletableFuture pays off when the pipeline itself needs composition, fan-out, or fine-grained timeouts.
Prerequisites
- Java 17+ (
orTimeout,completeOnTimeout,delayedExecutor,failedFuturearrived in Java 9) java.net.http.HttpClient(Java 11+)
Solution
1. Basic CompletableFuture
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
public class AsyncApiClient {
private static final HttpClient client = HttpClient.newHttpClient();
public static CompletableFuture<String> fetchAsync(String url) {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build();
return client.sendAsync(request, HttpResponse.BodyHandlers.ofString())
.thenApply(HttpResponse::body);
}
public static void main(String[] args) {
// Non-blocking — runs on the HttpClient's executor
CompletableFuture<String> future = fetchAsync("https://api.example.com/users");
// Do other work while the request is in flight...
// Block only when you need the result
String result = future.join();
System.out.println(result);
}
}
sendAsync already hands back a future, so the pipeline starts there. Every later stage — parse, transform, combine — attaches to that future instead of spawning new blocking calls.
2. Sequential Composition with thenCompose
import java.util.concurrent.CompletableFuture;
public class SequentialPipeline {
public static CompletableFuture<User> fetchUser(String userId) {
return fetchAsync("https://api.example.com/users/" + userId)
.thenApply(json -> parseUser(json));
}
public static CompletableFuture<List<Order>> fetchOrders(String userId) {
return fetchAsync("https://api.example.com/users/" + userId + "/orders")
.thenApply(json -> parseOrders(json));
}
public static CompletableFuture<UserProfile> buildProfile(String userId) {
// thenCompose chains futures — each step waits for the previous
return fetchUser(userId)
.thenCompose(user -> fetchOrders(user.id())
.thenApply(orders -> new UserProfile(user, orders)));
}
public static void main(String[] args) {
UserProfile profile = buildProfile("123").join();
System.out.println(profile);
}
}
thenCompose is the async version of flatMap: the lambda returns another future, and the result type stays flat. Use it whenever the next call needs data from the previous one — here the order lookup needs user.id(). Using thenApply in the same spot produces CompletableFuture<CompletableFuture<UserProfile>>, which is the classic mistake covered below.
3. Parallel Combination with thenCombine
import java.util.concurrent.CompletableFuture;
public class ParallelCombination {
public static CompletableFuture<Dashboard> buildDashboard(String userId) {
// All three fetches run in parallel
// fetchNotifications follows the same pattern as fetchOrders above
CompletableFuture<User> userFuture = fetchUser(userId);
CompletableFuture<List<Order>> ordersFuture = fetchOrders(userId);
CompletableFuture<List<Notification>> notifsFuture = fetchNotifications(userId);
// thenCombine merges two futures — runs after both complete
return userFuture
.thenCombine(ordersFuture, (user, orders) ->
new PartialDashboard(user, orders))
.thenCombine(notifsFuture, (partial, notifs) ->
new Dashboard(partial.user(), partial.orders(), notifs));
}
// Total time = max(fetchUser, fetchOrders, fetchNotifications), not sum
public static void main(String[] args) {
Dashboard dashboard = buildDashboard("123").join();
System.out.println(dashboard);
}
}
The three calls start the moment each fetch* runs — thenCombine only assembles results, it doesn’t launch anything. Chained thenCombine calls merge results pairwise; for four or more sources, allOf is easier to read.
4. allOf — Wait for All Futures
import java.util.concurrent.CompletableFuture;
import java.util.List;
import java.util.stream.Collectors;
public class AllOfPattern {
public static CompletableFuture<List<String>> fetchAllUrls(List<String> urls) {
// Start all fetches in parallel
List<CompletableFuture<String>> futures = urls.stream()
.map(AsyncApiClient::fetchAsync)
.collect(Collectors.toList());
// allOf returns a CompletableFuture<Void> — completes when all complete
CompletableFuture<Void> allDone = CompletableFuture.allOf(
futures.toArray(new CompletableFuture[0])
);
// After all complete, collect results
return allDone.thenApply(v ->
futures.stream()
.map(CompletableFuture::join) // Safe — all are complete
.collect(Collectors.toList())
);
}
public static void main(String[] args) {
List<String> urls = List.of(
"https://api.example.com/data/1",
"https://api.example.com/data/2",
"https://api.example.com/data/3"
);
List<String> results = fetchAllUrls(urls).join();
results.forEach(System.out::println);
}
}
Two details worth knowing. allOf returns CompletableFuture<Void> — it carries no results, so collecting them means join()ing each individual future after the aggregate completes (safe at that point, nothing blocks). And allOf fails fast: one exceptional completion fails the aggregate immediately while the other futures keep running — it doesn’t cancel them. When partial results are acceptable, attach handle or exceptionally to each future before wrapping them in allOf, so every future completes normally and the failures land in the collected list as fallbacks.
5. anyOf — First to Complete
import java.util.concurrent.CompletableFuture;
public class AnyOfPattern {
// Returns the first completed response — useful for racing replicas
public static CompletableFuture<String> fetchFirstAvailable(List<String> urls) {
CompletableFuture<?>[] futures = urls.stream()
.map(AsyncApiClient::fetchAsync)
.toArray(CompletableFuture[]::new);
// anyOf completes when the first future completes
return CompletableFuture.anyOf(futures)
.thenApply(obj -> (String) obj);
}
public static void main(String[] args) {
List<String> replicaUrls = List.of(
"https://replica1.example.com/data",
"https://replica2.example.com/data",
"https://replica3.example.com/data"
);
String result = fetchFirstAvailable(replicaUrls).join();
System.out.println("First response: " + result);
}
}
anyOf resolves on the first completion — success or failure. A fast 500 from one replica wins over a slow 200 from another, which is rarely what you want. For genuine “first success” semantics, give each future an exceptionally(ex -> null) filter and take the first non-null result, or fall back to a small loop over the completed futures.
6. Error Handling
import java.util.concurrent.CompletableFuture;
import java.util.logging.Logger;
public class ErrorHandling {
private static final Logger log = Logger.getLogger(ErrorHandling.class.getName());
public static CompletableFuture<String> fetchWithFallback(String url, String fallback) {
return fetchAsync(url)
// exceptionally — recover from failure with a fallback value
.exceptionally(ex -> {
log.warning(() -> "Fetch failed: " + ex.getMessage());
return fallback;
});
}
public static CompletableFuture<String> fetchWithRetry(String url, int maxRetries) {
return fetchAsync(url)
.handle((result, ex) -> {
if (ex != null) {
if (maxRetries > 0) {
log.info(() -> "Retrying (" + maxRetries + " left): " + ex.getMessage());
return fetchWithRetry(url, maxRetries - 1);
}
// Out of retries — propagate the failure
return CompletableFuture.<String>failedFuture(ex);
}
return CompletableFuture.completedFuture(result);
})
.thenCompose(f -> f); // Flatten nested CompletableFuture
}
// whenComplete — observe both branches without changing the result
public static CompletableFuture<String> fetchWithLogging(String url) {
return fetchAsync(url)
.whenComplete((result, ex) -> {
if (ex != null) {
log.severe(() -> "Request to " + url + " failed: " + ex.getMessage());
} else {
log.info(() -> "Request to " + url + " succeeded (" + result.length() + " bytes)");
}
});
}
public static void main(String[] args) {
String result = fetchWithFallback(
"https://api.example.com/maybe-down",
"{\"status\": \"fallback\"}"
).join();
System.out.println(result);
}
}
The three handlers do different jobs. exceptionally only runs on failure and must return a recovery value. handle sees both result and exception, so it can branch — this example uses it to retry, and failedFuture (Java 9+) keeps the last error visible instead of completing with null. whenComplete also sees both branches but returns the original outcome unchanged; it’s for logging and metrics, not recovery.
7. Custom Thread Pool
import java.net.URI;
import java.net.http.HttpClient;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CustomExecutorExample {
private static final HttpClient client = HttpClient.newHttpClient();
// A dedicated pool — don't rely on the common ForkJoinPool
private static final ExecutorService executor = Executors.newFixedThreadPool(
Runtime.getRuntime().availableProcessors(),
r -> {
Thread t = new Thread(r);
t.setName("async-worker-" + t.getId());
t.setDaemon(true);
return t;
}
);
// Any pre-existing synchronous call — client.send, a JDBC query, a file read
private static String blockingFetch(String url) {
try {
HttpRequest request = HttpRequest.newBuilder()
.uri(URI.create(url))
.GET()
.build();
return client.send(request, HttpResponse.BodyHandlers.ofString()).body();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
public static CompletableFuture<String> fetchWithCustomPool(String url) {
// supplyAsync runs the blocking call on the dedicated pool
return CompletableFuture.supplyAsync(() -> blockingFetch(url), executor);
}
public static CompletableFuture<UserProfile> buildProfileWithPool(String userId) {
// Reuses fetchUser/fetchOrders from the sequential example
return fetchUser(userId)
.thenComposeAsync(user -> fetchOrders(user.id())
.thenApplyAsync(orders -> new UserProfile(user, orders), executor),
executor);
}
public static void main(String[] args) {
try {
UserProfile profile = buildProfileWithPool("123").join();
System.out.println(profile);
} finally {
executor.shutdown();
}
}
}
Notice the nested thenApplyAsync inside thenComposeAsync — the inner lambda closes over user so new UserProfile(user, orders) still sees both values. Flattening the chain loses the outer variable, which is exactly why the sequential pipeline nests the same way. The *Async suffix is what pins each stage to executor instead of whatever thread happened to complete the upstream future.
8. Timeouts (Java 9+)
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class TimeoutExample {
public static CompletableFuture<String> fetchWithTimeout(String url) {
return fetchAsync(url)
.orTimeout(5, TimeUnit.SECONDS) // Complete exceptionally with TimeoutException
.exceptionally(ex -> {
if (ex instanceof java.util.concurrent.TimeoutException) {
return "{\"error\": \"request timed out\"}";
}
return "{\"error\": \"" + ex.getMessage() + "\"}";
});
}
// completeOnTimeout — provide a default value instead of an exception
public static CompletableFuture<String> fetchWithDefault(String url, String defaultValue) {
return fetchAsync(url)
.completeOnTimeout(defaultValue, 3, TimeUnit.SECONDS);
}
public static void main(String[] args) {
String result = fetchWithTimeout("https://slow-api.example.com/data").join();
System.out.println(result);
}
}
Both methods act on the future, not the work behind it. Neither cancels the in-flight HTTP request — the call keeps running in the background; the pipeline just stops waiting for it. Cancellation requires tracking the HttpRequest/CompletableFuture pair and calling cancel(true) yourself.
How It Works
The composition methods split along two axes: what the callback returns, and how many futures participate.
thenApply(Function<T, R>)maps the result with a plain function — the synchronous case.thenCompose(Function<T, CompletableFuture<R>>)flattens a nested future — the dependent-async case.thenCombine(other, (a, b) -> r)joins two independent futures. Both run in parallel; the callback fires after both complete.
The Async suffix changes where the callback runs, not what it does. thenApply executes on whichever thread completed the upstream future — often an HTTP client or I/O thread, so keep those callbacks cheap. thenApplyAsync/thenComposeAsync resubmit the callback to an executor, which is the right place for anything blocking or CPU-bound.
allOf and anyOf are aggregates over N futures. allOf completes when everything completes — or fails fast on the first exception, without cancelling the stragglers. anyOf completes on the first completion of any kind.
For timeouts, pick based on what a slow call should produce:
| Method | On deadline | Downstream sees |
|---|---|---|
orTimeout(t, unit) | Completes exceptionally with TimeoutException | Failure — handle with exceptionally/handle |
completeOnTimeout(v, t, unit) | Completes normally with v | Success — the fallback value flows through |
Both mutate the same future in place and return it, so they slot into a chain without extra variables. Remember the caveat from the Solution section: the underlying request isn’t cancelled, so a heavy timeout still costs a connection until the remote call finishes.
Variants
Retry with Exponential Backoff
public static CompletableFuture<String> fetchWithBackoff(
String url, int maxAttempts, long initialDelayMs) {
return fetchAsync(url)
.handle((result, ex) -> {
if (ex == null) {
return CompletableFuture.completedFuture(result);
}
if (maxAttempts <= 1) {
// Final attempt failed — propagate the error
return CompletableFuture.<String>failedFuture(ex);
}
long delay = initialDelayMs * (1L << (maxAttempts - 1));
// delayedExecutor returns an Executor, so it goes in supplyAsync's
// second argument — it has no supplyAsync method of its own
return CompletableFuture
.supplyAsync(() -> fetchWithBackoff(url, maxAttempts - 1, initialDelayMs),
CompletableFuture.delayedExecutor(delay, TimeUnit.MILLISECONDS))
.thenCompose(f -> f);
})
.thenCompose(f -> f);
}
CompletableFuture.delayedExecutor(delay, unit) returns a plain Executor that runs tasks after the delay — pass it as the executor argument to supplyAsync (or runAsync, thenApplyAsync, …). Calling supplyAsync on it doesn’t compile. With maxAttempts = 3 this makes three calls total: initial, then retries at initialDelay and 2×initialDelay — bump the shift or switch to Math.pow(2, attempt) if you want longer spacing.
Combining Results with Transformation
public static CompletableFuture<AggregatedReport> buildReport(
String userId, String dateRange) {
// fetchSales/fetchTraffic/fetchRevenue — service calls with the same
// shape as fetchUser: each returns CompletableFuture<SalesData> etc.
CompletableFuture<SalesData> sales = fetchSales(userId, dateRange);
CompletableFuture<TrafficData> traffic = fetchTraffic(userId, dateRange);
CompletableFuture<RevenueData> revenue = fetchRevenue(userId, dateRange);
return CompletableFuture.allOf(sales, traffic, revenue)
.thenApply(v -> {
// All three are complete — combine results
return new AggregatedReport(
sales.join(),
traffic.join(),
revenue.join()
);
});
}
Same allOf shape as the URL list, but typed: the individual futures keep their own result types and the joins happen only after the aggregate fires. If one source is optional, give it .exceptionally(ex -> SalesData.EMPTY) before allOf so its failure doesn’t take down the report.
Best Practices
- Always use custom executors:
supplyAsyncwithout an executor lands onForkJoinPool.commonPool(), shared withparallelStreamand everything else in the JVM. One blocking call can stall the whole pool — pass a dedicatedExecutorfor anything that isn’t pure CPU work. - Use
thenComposefor async chaining:thenApplywhose lambda returns a future produces nestedCompletableFuture<CompletableFuture<T>>.thenComposekeeps the chain flat. - Always handle exceptions: an exceptionally-completed future without
exceptionally/handlein the chain surfaces only atjoin()— usually as aCompletionExceptionfar from the real cause. Handle close to where the failure can still be named. - Set timeouts: without them, a hung call blocks
join()forever. UseorTimeout()for fail-fast orcompleteOnTimeout()for a graceful default. - Use
allOffor parallel fan-out: start everything first, aggregate second. Total latency is the slowest call, not the sum — the same idea asasyncio.gatherin Python. - Avoid
join()mid-pipeline:join()blocks the calling thread. Inside a pipeline, stay inthenCompose/thenCombine; block once at the end if you must.
Common Mistakes
- Assuming
allOfcancels stragglers: it doesn’t. After the aggregate fails, the other futures still run to completion and still consume connections and threads. Attach per-future handlers when a failure should short-circuit the batch, or when you need the partial results. - Blocking work on the common pool:
supplyAsyncwithout an executor uses the sharedForkJoinPool.commonPool(). Blocking there starves unrelated tasks — including the virtual-thread and parallel-stream machinery sharing the JVM. Always pass a custom executor. - Nesting
thenApplywith futures:thenApply(f -> fetchAsync(...))createsCompletableFuture<CompletableFuture<T>>. UsethenComposeto flatten. - Swallowing failures with
whenComplete:whenCompleteobserves but can’t recover — the exception still propagates. Useexceptionallyorhandlewhen the pipeline should produce a value despite the failure. - Not shutting down executors: custom pools keep their threads alive.
shutdown()them in afinallyblock or a shutdown hook, or the JVM won’t exit cleanly.
See Also
- CompletableFuture Javadoc — full method list, including the Java 9 additions used here
- Java 9 CompletableFuture improvements —
orTimeout,completeOnTimeout,delayedExecutor,failedFuture - ForkJoinPool Javadoc — why the common pool isn’t a general-purpose executor
- HttpClient Javadoc —
sendAsyncand its executor semantics - Runnable companion code — complete, compilable versions of these pipelines
- Concurrency Patterns Guide — where
CompletableFuturefits among the broader patterns
Frequently Asked Questions
What's the difference between thenApply and thenCompose?
thenApply takes Function<T, R> and returns CompletableFuture<R>; thenCompose takes Function<T, CompletableFuture<R>> and flattens the result to CompletableFuture<R>. If the callback calls another async method, you want thenCompose — thenApply would leave you with a CompletableFuture inside a CompletableFuture.
When should I use thenApplyAsync instead of thenApply?
When the callback blocks or burns CPU. thenApply runs on the thread that completed the upstream future — fine for cheap mapping, bad for parsing a 5MB payload or calling a blocking API. The Async variants move that work to your executor, where you control the pool size and thread names.
Why does allOf return CompletableFuture<Void>?
Because the input futures can each have a different result type — there's no generic way to merge them into one type-safe value. allOf is a barrier: once it completes, join() on each input future returns immediately with its own typed result.
How do I retry a failed CompletableFuture?
Wrap the call in a handle that returns either the completed result or a recursive retry — then flatten with thenCompose. For real delays between attempts, schedule the retry on CompletableFuture.delayedExecutor(delay, unit) passed as the executor argument to supplyAsync. Java 9's failedFuture(ex) is the clean way to propagate the final failure.
Does orTimeout cancel the underlying operation?
No. It completes the future exceptionally with TimeoutException, but the work behind it — the HTTP request, the database call — keeps running. To actually stop the operation you need to cancel it yourself: for HttpClient, keep the future returned by sendAsync and call cancel(true) on it.
Related Resources
Scale Concurrent Applications with Java Virtual Threads
Scale Java applications with virtual threads from Project Loom: Thread.ofVirtual, per-task executor, structured concurrency on JDK 25, and scoped values.
GuideConcurrency Patterns Guide
Production-ready concurrency patterns: thread pools, async/await, producer-consumer, semaphores, actors, circuit breakers in Python, Java, JS, Go, Elixir.
RecipeConcurrent Async Tasks with asyncio.gather and Task Groups
Compare asyncio.gather and TaskGroup in Python. Handle failures, cancellation, timeouts, concurrency limits, and results as tasks finish.
RecipeBuild Async Pipelines with C# async/await and Task.Run
Build async pipelines in C# using async/await, Task.Run, Task.WhenAll, Task.WhenAny, CancellationTokenSource, Channels, and Parallel.ForEachAsync for concurrent I/O and CPU work.
RecipeConcurrent Patterns with Go Goroutines and Channels
Build concurrent systems in Go using goroutines, channels, select statements, worker pools, fan-out/fan-in, pipelines, context cancellation, and rate limiting with tickers.
RecipeParallelize CPU and I/O Work with ThreadPoolExecutor
Use Python's ThreadPoolExecutor for parallel I/O operations, thread-safe result collection, Future callbacks, error handling, and mixing threads with asyncio for blocking work.