Introduction
Java 8 CompletableFuture arrived in March 2014 as the modern replacement for the rigid Future interface that shipped with Java 5 in 2004. The original Future could submit work to an ExecutorService and call get() to block for the result, but it had no way to register a callback, no way to compose two futures, and no way to recover from failure without throwing. Doug Lea's java.util.concurrent.CompletableFuture fixed all three problems by borrowing the design of Scala's Promise, JavaScript's Promises/A+, and ListenableFuture from Guava, and shipping it as a single class in the JDK.
For a Java learner, java 8 completablefuture is the gateway to writing non-blocking code on the JVM. It powers Spring WebFlux servers, the AWS SDK v2 async clients, and the JDBC Pool async APIs. This post shows how to create a CompletableFuture, chain transformations on it, combine multiple futures in parallel, and recover from exceptions, all without blocking the calling thread.
What is a Java 8 CompletableFuture?
A CompletableFuture is a Future that can be explicitly completed by calling complete() with a value or completeExceptionally() with a Throwable. Unlike Future, which is a passive handle you poll, a CompletableFuture is an active pipeline: methods like thenApply, thenAccept, thenCombine, and exceptionally attach callbacks that fire when the value becomes available. Each callback returns a new CompletableFuture, so the calls chain fluently into a non-blocking pipeline.
Conceptually, a CompletableFuture belongs to the family of asynchronous programming primitives, alongside Java's CompletionStage interface (which CompletableFuture implements), Reactive Streams Publisher, and JavaScript Promise. The crucial difference from blocking Future.get() is that the thread that starts the work is not the thread that has to wait for the work to finish. The callback model means the original thread can return immediately, and the JVM schedules the continuation on a worker thread when the result is ready.
How a CompletableFuture Works - Step by Step
Step 1: Create the future. Use supplyAsync(Supplier) to run a Supplier on the common ForkJoinPool and return a CompletableFuture that will be completed with the supplier's result. Use completedFuture(value) for an already-resolved value, or runAsync(Runnable) for a no-result task.
Step 2: Attach a transformation. thenApply(Function) takes the result, applies a function, and produces a new CompletableFuture of the function output. For example, supplyAsync(() -> fetchUser(id)).thenApply(User::getName) yields a CompletableFuture<String>.
Step 3: Attach a side effect. thenAccept(Consumer) consumes the value without returning anything, producing a CompletableFuture<Void>. thenRun(Runnable) runs an action that ignores the value. These are the terminal stages in a chain.
Step 4: Combine two futures. thenCombine(other, BiFunction) waits for both this and the other future, then applies a function to both results. allOf(f1, f2, ...) returns a CompletableFuture<Void> that completes when all inputs complete; anyOf(f1, f2, ...) completes when any input completes with its value.
Step 5: Recover from failures. exceptionally(Function<Throwable, T>) fires only if the upstream stage threw, and lets you substitute a fallback value. handle(BiFunction<T, Throwable, R>) fires on both success and failure and gives you access to either the value or the exception. whenComplete(BiConsumer) lets you observe the result without transforming it.
Java Program for CompletableFuture
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
public class CompletableFutureDemo {
// Simulate a slow remote call that returns a String
static String fetchUserName(int userId) {
sleep(150);
if (userId == 0) throw new RuntimeException("user not found");
return "User-" + userId;
}
// Simulate a slow lookup that returns an int
static int fetchCredit(int userId) {
sleep(120);
return 1000 + userId * 50;
}
static void sleep(long ms) {
try { Thread.sleep(ms); } catch (InterruptedException e) { }
}
public static void main(String[] args) throws Exception {
ExecutorService pool = Executors.newFixedThreadPool(4);
// (1) supplyAsync: start work on the pool, do not block
CompletableFuture<String> name = CompletableFuture.supplyAsync(
() -> fetchUserName(42), pool);
System.out.println("(1) submitted, main thread free");
// (2) thenApply: transform result, still non-blocking
CompletableFuture<String> upper = name.thenApply(String::toUpperCase);
// (3) thenAccept: consume result (terminal)
CompletableFuture<Void> printed = upper.thenAccept(u ->
System.out.println("(2)(3) got name: " + u));
printed.join(); // block until the chain finishes for the demo
System.out.println("--- chain finished ---");
// (4) thenCombine: combine two independent futures
CompletableFuture<Integer> credit = CompletableFuture.supplyAsync(
() -> fetchCredit(42), pool);
CompletableFuture<String> summary = name.thenCombine(credit,
(n, c) -> n + " has credit " + c);
System.out.println("(4) combined: " + summary.join());
// (5) allOf: wait for three independent calls in parallel
long t0 = System.currentTimeMillis();
CompletableFuture<String> a = CompletableFuture.supplyAsync(
() -> { sleep(100); return "A"; }, pool);
CompletableFuture<String> b = CompletableFuture.supplyAsync(
() -> { sleep(100); return "B"; }, pool);
CompletableFuture<String> c = CompletableFuture.supplyAsync(
() -> { sleep(100); return "C"; }, pool);
CompletableFuture<Void> all = CompletableFuture.allOf(a, b, c);
all.join();
System.out.println("(5) allOf in " + (System.currentTimeMillis() - t0) + " ms");
System.out.println(" results: " + a.join() + ", " + b.join() + ", " + c.join());
// (6) exceptionally: recover from a failure
CompletableFuture<String> safe = CompletableFuture
.supplyAsync(() -> fetchUserName(0), pool)
.exceptionally(ex -> "FALLBACK(" + ex.getMessage() + ")");
System.out.println("(6) recovered: " + safe.join());
// (7) handle: branch on success or failure
CompletableFuture<String> handled = CompletableFuture
.supplyAsync(() -> fetchUserName(0), pool)
.handle((v, ex) -> {
if (ex != null) return "ERR";
return v.toUpperCase();
});
System.out.println("(7) handle: " + handled.join());
pool.shutdown();
pool.awaitTermination(5, TimeUnit.SECONDS);
}
}
Code Explanation - Line by Line
The fetchUserName and fetchCredit methods simulate slow I/O by sleeping for 150 and 120 milliseconds. The Thread.sleep call is wrapped in a try-catch that swallows InterruptedException so the demo code stays readable; in production you should restore the interrupt status with Thread.currentThread().interrupt(). The sleep helper centralises this so each method body stays focused on the business logic.
In the main method, section (1) calls supplyAsync with a Supplier and an explicit ExecutorService. The Supplier lambda runs on the pool, the calling thread does not block, and the returned CompletableFuture<String> is a handle to the eventual result. Using an explicit pool is important because the default common ForkJoinPool is shared across the entire JVM and is sized to one less thread than the number of CPU cores, which is too small for I/O-bound work.
Section (2) chains thenApply to transform the future value. The Function is String::toUpperCase, so a CompletableFuture<String> named "User-42" becomes a CompletableFuture<String> named "USER-42". Crucially, thenApply returns a new future; the original name future is left untouched. Section (3) chains thenAccept to consume the value; the lambda prints the result and returns nothing, so the return type is CompletableFuture<Void>.
Section (4) demonstrates thenCombine. We start an independent future credit, then combine it with name using a BiFunction that takes the two results and produces a single combined string. The combined future does not complete until both inputs have completed, and the combine function runs on whichever thread completes the second of the two inputs.
Section (5) shows the parallelism win of allOf. Three futures that each sleep for 100 milliseconds are submitted at the same time; allOf returns a future that completes when all three have completed. Because the work runs in parallel on three threads, the total elapsed time is roughly 100 milliseconds rather than 300, which the printed elapsed time confirms. allOf itself returns CompletableFuture<Void>, so to read the results you call .join() on each input future after allOf has completed.
Section (6) demonstrates exception recovery. We deliberately submit a task that throws RuntimeException, then attach exceptionally, which takes a Function<Throwable, T>. The function inspects the exception and returns the fallback value "FALLBACK(...)". The downstream future is then completed normally with that fallback value, so join() returns it without throwing.
Section (7) shows handle, which takes a BiFunction<T, Throwable, R>. The function receives either a non-null value and a null throwable (on success) or a null value and a non-null throwable (on failure). That makes handle the right tool when you need to transform both branches uniformly. Finally, the pool is shut down and awaitTermination waits up to five seconds for outstanding tasks to finish.
Sample Input and Output
(1) submitted, main thread free
(2)(3) got name: USER-42
--- chain finished ---
(4) combined: User-42 has credit 3100
(5) allOf in 105 ms
results: A, B, C
(6) recovered: FALLBACK(user not found)
(7) handle: ERR
The output confirms every callback contract. The name appears uppercased because thenApply ran toUpperCase before thenAccept printed. The combined string contains both the user name and the credit because thenCombine waited for both inputs. allOf ran in about 100 ms instead of 300 ms because the three sleep tasks ran in parallel. The fallback text from exceptionally proves that the upstream exception was caught. Finally the "ERR" string from handle proves that the failure branch was exercised.
Common Mistakes to Avoid
The first mistake is calling get() or join() immediately after supplyAsync, which turns the asynchronous API back into a blocking one. The whole point of CompletableFuture is to attach a callback chain so the calling thread can continue; if you must block, do it at the end of the chain and only in code where blocking is unavoidable such as a main method or a unit test. The second mistake is using the default common ForkJoinPool for I/O-bound work. That pool is sized to one fewer thread than CPU cores and is shared by every parallel stream in the JVM, so blocking I/O tasks on it quickly starve CPU-bound work.
The third mistake is forgetting that thenApply, thenAccept, and thenRun run on whichever thread completed the upstream stage. If the upstream stage completed before the callback was attached, the callback runs synchronously on the calling thread; if it completed afterwards, the callback runs on the pool thread. To control this, use the Async variants thenApplyAsync, thenAcceptAsync, and thenRunAsync, which always schedule the callback on a pool.
The fourth mistake is swallowing exceptions silently. If a stage throws and no exceptionally or handle is attached downstream, the exception propagates as a CompletionException wrapping the original cause. If you call join() on a future that completed exceptionally, the exception is thrown as a CompletionException at that point, which can surprise you in code far from where the actual failure happened. Always attach an exceptionally or handle stage at the end of every chain that might fail.
The fifth mistake is mutating shared state inside a callback without synchronisation. The callbacks run on pool threads, so concurrent access to non-thread-safe collections or counters will race. Use ConcurrentHashMap, AtomicLong, or compute-blocking patterns instead of mutating a plain HashMap from inside thenAccept.
Real-World Applications
CompletableFuture powers the modern async Java stack. Spring WebFlux uses it under the hood for the Mono and Flux reactive types when the underlying publisher is a CompletableFuture. The AWS SDK for Java v2 exposes every client operation as a CompletableFuture-returning async variant, used by Lambda handlers that must not block the event-loop thread. The Apache HttpClient 5 async API and the Java 11 HttpClient sendAsync method both return CompletionStage and CompletableFuture respectively.
In the JDK itself, CompletableFuture is the return type of java.util.concurrent.ExecutorService.submit when wrapped, and it underpins the new public API surface of java.net.http.HttpClient since Java 11. The Kotlin Coroutines JVM library bridges to CompletableFuture via Future.await, and Scala's Future.fromJavaFuture wraps a CompletableFuture for Scala code that consumes Java libraries. Understanding java 8 completablefuture is therefore the entry ticket to reactive programming, async I/O, and modern non-blocking server design on the JVM, and the same composition model that powers java 8 completablefuture underpins every reactive-streams library on the JVM.
Conclusion
We showed how to create a CompletableFuture with supplyAsync, transform it with thenApply, consume it with thenAccept, combine two futures with thenCombine, wait for many futures in parallel with allOf, and recover from failures with exceptionally and handle. CompletableFuture is the bridge between blocking Future and reactive code, and it composes the way modern Java servers need: non-blocking, callback-driven, and resilient. The natural next topics to study are the Java 11 HttpClient that returns CompletableFuture from sendAsync, and Project Reactor or Mutiny, the reactive-streams libraries that build on the same composition model.
Comments
Comments
Post a Comment