Java CompletableFuture
Java CompletableFuture is a Future you can build pipelines with. Instead of blocking on get() and then deciding what to do, you tell a CompletableFuture what to do when the result arrives: transform it, combine it with another result, or recover from an error.
CompletableFuture was added in Java 8 in the java.util.concurrent package. It implements both Future and CompletionStage, so everything from the Java Future interface lesson still works, plus dozens of methods for non-blocking asynchronous programming.
Java CompletableFuture vs Future
A plain Future can only be waited on. CompletableFuture adds callbacks, chaining, combining and error handling.
| Feature | Future | CompletableFuture |
|---|---|---|
| Wait for the result | get() | get() or join() |
| Run a step when the result arrives | No | thenApply, thenAccept, thenRun |
| Chain another async call | No | thenCompose |
| Combine two results | No | thenCombine, allOf, anyOf |
| Recover from errors | No | exceptionally, handle, whenComplete |
| Complete it yourself | No | complete, completeExceptionally |
| Built-in timeouts | Only get(timeout) | orTimeout, completeOnTimeout |
Creating a CompletableFuture with supplyAsync and runAsync
Two static factory methods start asynchronous work:
| Method | Task type | Returns |
|---|---|---|
supplyAsync(Supplier<T>) | Produces a value | CompletableFuture<T> |
runAsync(Runnable) | Produces no value | CompletableFuture<Void> |
Both have an overload that takes an Executor. Without one, the task runs in the shared ForkJoinPool.commonPool().
import java.util.concurrent.CompletableFuture;
public class CreateCompletableFuture {
public static void main(String[] args) {
CompletableFuture<String> greeting = CompletableFuture.supplyAsync(
() -> "Hello from " + Thread.currentThread().getName());
CompletableFuture<Void> logTask = CompletableFuture.runAsync(
() -> System.out.println("Logging on " + Thread.currentThread().getName()));
System.out.println(greeting.join()); // join() waits like get()
logTask.join();
}
}
Output from one run on a multi-core machine (worker numbers can differ; on a single-core machine Java uses a new plain thread for each async task instead of the common pool):
Logging on ForkJoinPool.commonPool-worker-2
Hello from ForkJoinPool.commonPool-worker-1
How it works:
supplyAsync()runs the lambda on a common-pool thread and completes the future with its return value.runAsync()runs aRunnable; its future completes withnullwhen the code finishes.join()waits for the result likeget(), but throws an uncheckedCompletionExceptioninstead of the checkedExecutionException, so it fits nicely into lambdas and streams.
Note: Common-pool threads are daemon threads. If
mainends before an async task finishes, the JVM can exit and the task is lost. Alwaysjoin()the futures you care about.
Transforming Results with thenApply
thenApply(Function) returns a new CompletableFuture holding the function applied to the previous result. Calls can be chained, and each step runs as soon as the step before it completes.
import java.util.concurrent.CompletableFuture;
public class ThenApplyDemo {
public static void main(String[] args) {
CompletableFuture<String> headline = CompletableFuture
.supplyAsync(() -> " java completablefuture tutorial ") // raw input
.thenApply(String::strip) // remove spaces
.thenApply(String::toUpperCase) // make it shout
.thenApply(text -> text + " (" + text.length() + " chars)");
System.out.println(headline.join());
}
}
Output:
JAVA COMPLETABLEFUTURE TUTORIAL (31 chars)
How it works:
- Each
thenApply()registers a step and immediately returns a new future. No step blocks the main thread. - The steps run in order: strip, then uppercase, then add the length.
- Only
join()at the end waits, and by then the whole pipeline has run.
Consuming Results with thenAccept and thenRun
Some steps do not produce a new value. thenAccept(Consumer) receives the result and returns nothing. thenRun(Runnable) ignores the result and just runs after the previous step.
import java.util.concurrent.CompletableFuture;
public class ThenAcceptDemo {
public static void main(String[] args) {
CompletableFuture<Void> pipeline = CompletableFuture
.supplyAsync(() -> 1250.0) // order total
.thenApply(total -> total * 1.18) // add 18% GST
.thenAccept(withTax -> System.out.printf("Total with GST: Rs. %.2f%n", withTax))
.thenRun(() -> System.out.println("Invoice sent to the customer"));
pipeline.join();
}
}
Output:
Total with GST: Rs. 1475.00
Invoice sent to the customer
How it works:
thenApply()turns1250.0into1475.0.thenAccept()prints the value and returns aCompletableFuture<Void>.thenRun()has no input at all; it simply runs once the printing step is done.
| Method | Input | Output |
|---|---|---|
thenApply(Function<T,U>) | previous result | new value U |
thenAccept(Consumer<T>) | previous result | Void |
thenRun(Runnable) | nothing | Void |
Chaining Async Calls with thenCompose
When the next step is itself asynchronous and returns a CompletableFuture, thenApply() would give you a nested CompletableFuture<CompletableFuture<T>>. thenCompose() flattens it, like flatMap in Java streams.
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class ThenComposeDemo {
// Each method simulates a call to a remote service
static CompletableFuture<Integer> findUserId(String email) {
return CompletableFuture.supplyAsync(() -> email.equals("asha@gocourse.in") ? 7 : -1);
}
static CompletableFuture<List<String>> findCourses(int userId) {
return CompletableFuture.supplyAsync(() -> List.of("Java Basics", "Java Multithreading"));
}
public static void main(String[] args) {
// thenApply would give CompletableFuture<CompletableFuture<List<String>>>
CompletableFuture<CompletableFuture<List<String>>> nested =
findUserId("asha@gocourse.in").thenApply(id -> findCourses(id));
// thenCompose flattens it to CompletableFuture<List<String>>
CompletableFuture<List<String>> courses =
findUserId("asha@gocourse.in").thenCompose(id -> findCourses(id));
System.out.println("nested : " + nested.join().join());
System.out.println("flat : " + courses.join());
}
}
Output:
nested : [Java Basics, Java Multithreading]
flat : [Java Basics, Java Multithreading]
How it works:
findCourses()returns a future, so mapping withthenApply()wraps a future inside a future. You would have to calljoin()twice.thenCompose()waits for the inner future and returns its result directly, so the chain stays flat and readable.
Note: Use
thenApply()when the next step returns a plain value. UsethenCompose()when the next step returns aCompletableFuture.
Combining Two Futures with thenCombine
thenCombine() waits for two independent futures and merges their results with a BiFunction. Both tasks run at the same time.
import java.util.concurrent.CompletableFuture;
public class ThenCombineDemo {
static void sleep(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
CompletableFuture<Double> priceInUsd = CompletableFuture.supplyAsync(() -> {
sleep(400); // product service
return 49.99;
});
CompletableFuture<Double> usdToInr = CompletableFuture.supplyAsync(() -> {
sleep(300); // currency service
return 84.00;
});
CompletableFuture<String> priceInInr = priceInUsd.thenCombine(usdToInr,
(usd, rate) -> String.format("Rs. %.2f", usd * rate));
System.out.println("Price: " + priceInInr.join());
System.out.println("Took about " + Math.round((System.currentTimeMillis() - start) / 100.0) * 100 + " ms");
}
}
Output:
Price: Rs. 4199.16
Took about 400 ms
How it works:
- The product call (400 ms) and the currency call (300 ms) run in parallel.
thenCombine()fires only when both are done, so the total time is about 400 ms, not 700 ms.- The lambda receives both results, multiplies them and formats the price.
Waiting for Many Futures with allOf and anyOf
| Method | Completes when | Result type |
|---|---|---|
CompletableFuture.allOf(cf...) | all futures complete | CompletableFuture<Void> |
CompletableFuture.anyOf(cf...) | the first future completes | CompletableFuture<Object> |
import java.util.List;
import java.util.concurrent.CompletableFuture;
public class AllOfAnyOfDemo {
static CompletableFuture<String> fetchFrom(String mirror, long delayMs) {
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(delayMs);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return mirror;
});
}
public static void main(String[] args) {
List<CompletableFuture<String>> mirrors = List.of(
fetchFrom("mirror-asia", 300),
fetchFrom("mirror-europe", 100),
fetchFrom("mirror-us", 200));
// anyOf: use whichever mirror answers first
Object fastest = CompletableFuture.anyOf(mirrors.toArray(new CompletableFuture[0])).join();
System.out.println("Fastest mirror: " + fastest);
// allOf: wait for every mirror, then collect the results
CompletableFuture.allOf(mirrors.toArray(new CompletableFuture[0])).join();
List<String> all = mirrors.stream().map(CompletableFuture::join).toList();
System.out.println("All mirrors : " + all);
}
}
Output:
Fastest mirror: mirror-europe
All mirrors : [mirror-asia, mirror-europe, mirror-us]
How it works:
anyOf()completes after about 100 ms with the result of the fastest future. Its type isObject, because the futures could hold different types.allOf()returnsCompletableFuture<Void>; it carries no results itself. After it completes,join()on each original future returns instantly.- The final list keeps the original order, not the order in which the mirrors finished.
Handling Errors: exceptionally, handle and whenComplete
When a step throws, the exception travels down the chain and every later thenApply/thenAccept step is skipped until a recovery method catches it.
| Method | Called when | Can change the result? |
|---|---|---|
exceptionally(Function<Throwable,T>) | only on failure | Yes, returns a fallback value |
handle(BiFunction<T,Throwable,U>) | always | Yes, gets result or error |
whenComplete(BiConsumer<T,Throwable>) | always | No, for logging and side effects |
import java.util.concurrent.CompletableFuture;
public class ErrorHandlingDemo {
static CompletableFuture<Integer> parseQuantity(String input) {
return CompletableFuture.supplyAsync(() -> Integer.parseInt(input));
}
public static void main(String[] args) {
// 1. exceptionally: replace a failure with a default value
int quantity = parseQuantity("five")
.thenApply(q -> q * 2) // skipped, because parsing failed
.exceptionally(error -> {
System.out.println("exceptionally caught: " + error.getCause().getMessage());
return 1; // default quantity
})
.join();
System.out.println("quantity = " + quantity);
// 2. handle: look at the result or the error in one place
for (String input : new String[] {"12", "twelve"}) {
String message = parseQuantity(input).handle((value, error) ->
error == null ? "valid quantity " + value : "invalid input '" + input + "'").join();
System.out.println("handle -> " + message);
}
// 3. whenComplete: log without changing the outcome
parseQuantity("7")
.whenComplete((value, error) -> System.out.println("whenComplete saw value=" + value + ", error=" + error))
.join();
}
}
Output:
exceptionally caught: For input string: "five"
quantity = 1
handle -> valid quantity 12
handle -> invalid input 'twelve'
whenComplete saw value=7, error=null
How it works:
Integer.parseInt("five")throwsNumberFormatException. ThethenApply()step is skipped, andexceptionally()returns1instead.- Inside the chain, the error usually arrives wrapped in a
CompletionException, which is why the code readserror.getCause(). handle()receives two arguments; exactly one is non-null. It turns both outcomes into a message.whenComplete()observes the outcome but passes the original result (or exception) through unchanged.
Note: If a failed future reaches
join()without being handled,join()throws aCompletionExceptionandget()throws anExecutionException, each with the original exception as the cause.
Timeouts with orTimeout and completeOnTimeout
Java 9 added two timeout methods that need no blocking get(timeout) call:
orTimeout(time, unit)completes the future exceptionally with aTimeoutException.completeOnTimeout(value, time, unit)completes it normally with a fallback value.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.TimeUnit;
public class TimeoutDemo {
static CompletableFuture<String> slowWeatherService() {
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "Chennai: 31°C, humid";
});
}
public static void main(String[] args) {
String withFallback = slowWeatherService()
.completeOnTimeout("Weather unavailable", 500, TimeUnit.MILLISECONDS)
.join();
System.out.println(withFallback);
String withError = slowWeatherService()
.orTimeout(500, TimeUnit.MILLISECONDS)
.exceptionally(error -> "Failed: " + error.getClass().getSimpleName())
.join();
System.out.println(withError);
}
}
Output:
Weather unavailable
Failed: TimeoutException
How it works:
- Both calls take 2 seconds, longer than the 500 ms limit.
completeOnTimeout()finishes the future with the fallback string after 500 ms.orTimeout()fails the future with aTimeoutException, whichexceptionally()turns into a message.- Neither timeout stops the underlying task; it simply no longer matters to the caller.
Running Steps on Your Own Executor
Every thenXxx method has an Async variant (thenApplyAsync, thenAcceptAsync, ...) that runs the step as a new task, optionally on an executor you choose. For blocking I/O, a dedicated executor, such as one that uses Java virtual threads, keeps the common pool free for CPU work.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CustomExecutorDemo {
public static void main(String[] args) {
try (ExecutorService ioExecutor = Executors.newFixedThreadPool(2, runnable -> {
Thread thread = new Thread(runnable);
thread.setName("io-" + thread.threadId());
return thread;
})) {
String result = CompletableFuture
.supplyAsync(() -> "file.csv read on " + Thread.currentThread().getName(), ioExecutor)
.thenApplyAsync(text -> text + " | parsed on " + Thread.currentThread().getName())
.join();
System.out.println(result);
}
}
}
Output from one run (thread numbers can differ):
file.csv read on io-22 | parsed on ForkJoinPool.commonPool-worker-1
How it works:
supplyAsync(supplier, ioExecutor)runs the read step on the custom pool, whose threads are namedio-<id>.thenApplyAsync()without an executor schedules the next step on the common pool.- Closing the executor in the try-with-resources block shuts down its threads cleanly.
Completing a CompletableFuture Manually
You can create an empty CompletableFuture and complete it later from any thread with complete(value) or completeExceptionally(error). This is how callback-based APIs are turned into futures.
import java.util.concurrent.CompletableFuture;
public class ManualCompletion {
public static void main(String[] args) {
CompletableFuture<String> paymentResult = new CompletableFuture<>();
// Somebody waits for the payment and reacts to it
CompletableFuture<Void> receipt = paymentResult
.thenAccept(status -> System.out.println("Receipt printed: " + status));
// Some other thread (a payment gateway callback) completes it later
Thread gatewayCallback = new Thread(() -> {
System.out.println("Gateway callback received");
paymentResult.complete("PAID - txn 88231");
});
gatewayCallback.start();
receipt.join();
System.out.println("Second complete() accepted? " + paymentResult.complete("PAID again"));
}
}
Output:
Gateway callback received
Receipt printed: PAID - txn 88231
Second complete() accepted? false
How it works:
new CompletableFuture<>()creates a future with no task behind it.thenAccept()registers a step that runs as soon as anyone completes the future.- The callback thread calls
complete(), which triggers the receipt step. - A future can be completed only once. Later calls to
complete()returnfalseand are ignored.
Real-World Example: A Travel Booking Aggregator
A travel site searches for the cheapest flight and a hotel at the same time, applies a discount coupon from a third service, and must answer within 800 ms. Hotel search is optional: if it fails, the site shows the flight alone.
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class TravelAggregator {
record Flight(String airline, int price) { }
record Hotel(String name, int pricePerNight) { }
record Quote(Flight flight, Hotel hotel, int nights, int discountPercent) {
int total() {
int hotelCost = hotel == null ? 0 : hotel.pricePerNight() * nights;
return (flight.price() + hotelCost) * (100 - discountPercent) / 100;
}
}
static void pause(long millis) {
try {
Thread.sleep(millis);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
// --- simulated remote services ---
static List<Flight> searchFlights(String route) {
pause(300);
return List.of(new Flight("SkyJet", 5400), new Flight("IndiAir", 4850), new Flight("BlueWing", 6100));
}
static Hotel searchHotel(String city) {
pause(250);
if (city.equals("Goa")) {
throw new IllegalStateException("hotel API rate limit exceeded");
}
return new Hotel("Sea View Inn", 3200);
}
static int couponDiscount(String code) {
pause(150);
return code.equals("TRAVEL10") ? 10 : 0;
}
static CompletableFuture<String> buildQuote(String route, String city, int nights,
String coupon, ExecutorService io) {
CompletableFuture<Flight> cheapestFlight = CompletableFuture
.supplyAsync(() -> searchFlights(route), io)
.thenApply(flights -> flights.stream()
.min((a, b) -> Integer.compare(a.price(), b.price()))
.orElseThrow());
CompletableFuture<Hotel> hotel = CompletableFuture
.supplyAsync(() -> searchHotel(city), io)
.exceptionally(error -> null); // optional: continue without a hotel
CompletableFuture<Integer> discount = CompletableFuture
.supplyAsync(() -> couponDiscount(coupon), io)
.completeOnTimeout(0, 200, TimeUnit.MILLISECONDS);
return cheapestFlight
.thenCombine(hotel, (flight, stay) -> new Quote(flight, stay, nights, 0))
.thenCombine(discount, (quote, percent) ->
new Quote(quote.flight(), quote.hotel(), quote.nights(), percent))
.thenApply(quote -> String.format("%-17s flight %s Rs.%d | hotel %s | %d%% off | total Rs.%d",
route, quote.flight().airline(), quote.flight().price(),
quote.hotel() == null ? "not available" : quote.hotel().name(),
quote.discountPercent(), quote.total()))
.orTimeout(800, TimeUnit.MILLISECONDS)
.exceptionally(error -> route + ": search failed, please try again");
}
public static void main(String[] args) {
long start = System.currentTimeMillis();
try (ExecutorService io = Executors.newFixedThreadPool(6)) {
CompletableFuture<String> toDelhi = buildQuote("Chennai -> Delhi", "Delhi", 2, "TRAVEL10", io);
CompletableFuture<String> toGoa = buildQuote("Chennai -> Goa", "Goa", 3, "NOCODE", io);
CompletableFuture.allOf(toDelhi, toGoa).join();
System.out.println(toDelhi.join());
System.out.println(toGoa.join());
}
System.out.println("Both searches done in about "
+ Math.round((System.currentTimeMillis() - start) / 100.0) * 100 + " ms");
}
}
Output:
Chennai -> Delhi flight IndiAir Rs.4850 | hotel Sea View Inn | 10% off | total Rs.10125
Chennai -> Goa flight IndiAir Rs.4850 | hotel not available | 0% off | total Rs.4850
Both searches done in about 400 ms
How it works:
- Three parallel calls per search. Flights, hotel and coupon run at the same time on the
iopool, so one search takes about as long as the slowest call (300 ms), not the sum (700 ms). - thenApply picks the cheapest flight. The stream inside
thenApply()reduces the list to the lowest price: IndiAir at Rs. 4850. - Optional hotel. For Goa,
searchHotel()throws.exceptionally(error -> null)turns the failure into "no hotel", so the rest of the chain still runs. - thenCombine merges the results. The first
thenCombine()joins flight and hotel into aQuote; the second adds the discount. For Delhi: (4850 + 3200 × 2) × 90% = Rs. 10,125. - Timeouts at two levels. The coupon call falls back to 0% after 200 ms with
completeOnTimeout(), andorTimeout(800 ms)protects the whole quote, turning a slow search into a friendly error message. - Two searches at once.
allOf()waits for both routes. Because they also run in parallel, both answers are ready in under half a second: about 300 ms of waiting plus thread start-up on the first run.
For the simpler blocking model this lesson builds on, see Java Future Interface. The thread pools behind these futures are explained in Java ExecutorService.