Threads ·
‹ Previous Next ›
⏱ 5 min read Modified: 2026-11-24

CompletableFuture in Java: Chaining Asynchronous Tasks

CompletableFuture is a class in java.util.concurrent (Java 8) that implements both Future and CompletionStage. It is a Future you can complete by hand and attach continuations to — thenApply, thenCompose, thenCombine and others — instead of blocking in get(), which makes it the standard tool for asynchronous programming in Java. You start an async task with the static methods supplyAsync() (returns a value) and runAsync() (no value), and each continuation runs as soon as the previous stage is ready.

CompletableFuture<String> greeting = CompletableFuture
        .supplyAsync(() -> "java")            // runs in another thread
        .thenApply(String::toUpperCase)        // when ready, transform it
        .thenApply(s -> "Hello, " + s);
System.out.println(greeting.join());           // Output: Hello, JAVA

Drop the final join() from a similar program, and the task may simply never run. CompletableFuture.runAsync(() -> { pause(500); System.out.println("Report sent"); }) at the end of main prints nothing: the task went to ForkJoinPool.commonPool(), whose threads are daemons, and the JVM exited without waiting for them. No exception, no warning. The details are in supplyAsync and runAsync.

Future vs CompletableFuture: What Future Can’t Do

A plain Future from an ExecutorService can do exactly one thing: hand over the result through a blocking get(). You can’t say “when the result is ready, do this with it”, you can’t chain two tasks so the second starts when the first finishes, and you can’t combine the results of several tasks without waiting on each one by hand. CompletableFuture closes all three gaps.

With a Future, the thread that needs the result has to sit in get() doing nothing. The Future methods themselves — get(timeout), isDone(), cancel() — are covered in Future: get(), Timeouts and Cancelling a Task; what matters here is what the interface lacks.

Capability Future (FutureTask from submit()) CompletableFuture
Get the result Only blocking get() / get(timeout, unit) join(), get(), non-blocking getNow(default)
Continue when ready No thenApply, thenAccept, thenRun, thenCompose
Combine several tasks By hand: get() one by one, or invokeAll() thenCombine, allOf, anyOf
Complete manually No — only the task itself sets the result complete(value), completeExceptionally(ex)
Handle an error try/catch around get(), ExecutionException Inside the chain: exceptionally, handle, whenComplete
Timeout Only on waiting: get(timeout, unit) On the result itself: orTimeout, completeOnTimeout (Java 9)
cancel(true) Interrupts the thread running the task Doesn’t interrupt: the future is marked cancelled, the task keeps running

All the chaining methods are declared in the CompletionStage interface: a “stage” of a computation that completes and then triggers the stages depending on it. CompletableFuture is its main implementation in the JDK, which is why API signatures (for example, the async HttpClient.sendAsync() from Java 11) sometimes use CompletableFuture and sometimes CompletionStage.

supplyAsync and runAsync: Starting an Async Task

CompletableFuture.supplyAsync(Supplier) starts a task that returns a value, and runAsync(Runnable) starts one that doesn’t (CompletableFuture<Void>). Without a second argument the task runs in the shared ForkJoinPool.commonPool(); pass your own Executor as the second argument to change that. Both methods return immediately, without waiting for the task.

Method Task Where it runs
supplyAsync(Supplier<T>) T get() — returns a value ForkJoinPool.commonPool()
supplyAsync(Supplier<T>, Executor) Same The pool you pass in
runAsync(Runnable) void run(), result is CompletableFuture<Void> ForkJoinPool.commonPool()
runAsync(Runnable, Executor) Same The pool you pass in

The main catch with the default pool: every ForkJoinPool worker thread is a daemon. The JVM exits once all non-daemon threads have finished (the rule is explained in The main Thread and When a Program Ends), and unfinished tasks in commonPool don’t keep it alive. What does this code print?

import java.util.concurrent.CompletableFuture;

public class DaemonPitfall {
    public static void main(String[] args) {
        CompletableFuture<Void> report = CompletableFuture.runAsync(() -> {
            pause(500);
            System.out.println("Report sent");
        });
        System.out.println("main finished");
        // report.join();   // uncomment this, and the report gets sent
    }

    static void pause(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
main finished

“Report sent” never shows up. Uncomment report.join() and the output is complete: main waits for the task, and the second line appears half a second later. That’s why every example in this lesson ends main with a join(). In a server application the JVM lives long anyway, but in a console program or a test, a task you don’t wait for is lost silently.

There’s a less obvious detail in the Javadoc: if the parallelism of commonPool is below two, CompletableFuture doesn’t use it at all and creates a new thread for each async task. The default parallelism is the number of cores minus one, so on a machine or container with 1–2 CPUs, DaemonPitfall may behave differently and print both lines. Code that “works on my laptop and loses tasks on the server” (or the other way round) is a reason to check whether it actually waits for its results.

Pass your own Executor as the second argument when tasks block: read files, query a database, call over the network. The pool is usually created through Executors (which one to pick is covered in The Executors Factory) and you close it yourself — CompletableFuture won’t do it for you.

try (ExecutorService io = Executors.newFixedThreadPool(10)) {
    CompletableFuture<String> page = CompletableFuture.supplyAsync(() -> download(url), io);
    System.out.println(page.join().length());
}   // close() waits for the tasks and stops the pool threads

Keep blocking I/O out of commonPool

There is one commonPool per JVM: parallel streams and every *Async method without its own pool run there too. It has as many threads as cores minus one, and a dozen tasks waiting on a slow service will occupy all of them — every other async computation in the application then waits in the queue. For tasks that wait on the network or the disk, pass a separate Executor.

One more detail of the signatures: Supplier.get() and Runnable.run() declare no checked exceptions, unlike Callable.call() (compared in Callable vs Runnable). Files.readString() inside supplyAsync won’t compile without a try/catch; the usual fix is to wrap the IOException in an UncheckedIOException, which the chain then handles like any other exception.

join(), get(), getNow() and complete(): Getting the Result

You get the result of a CompletableFuture with the blocking join() or get(), or with the non-blocking getNow(default). join() throws the unchecked CompletionException, so it fits nicely into lambdas and streams; get() throws the checked ExecutionException and InterruptedException, just like a plain Future. To complete a future by hand, use complete() and completeExceptionally().

Method What it does Error or edge case
T join() Waits and returns the result CompletionException (unchecked), the cause is in getCause(); CancellationException after cancellation
T get() Waits and returns the result ExecutionException and InterruptedException (checked), CancellationException
T get(long, TimeUnit) Waits no longer than the timeout TimeoutException; the task itself keeps running
T getNow(T valueIfAbsent) Doesn’t wait: the result if ready, otherwise valueIfAbsent If the future completed with an error — CompletionException; if it was cancelled — CancellationException
boolean complete(T value) Completes the future with a value if it isn’t completed yet false if the future is already completed — the value stays the same
boolean completeExceptionally(Throwable) Completes the future with an exception false if already completed
completedFuture(value), failedFuture(ex) Static: an already-completed future with a result or an error (failedFuture — Java 9) Handy in tests and as a stub instead of a real call
resultNow(), exceptionNow(), state() Java 19: result, exception or state without waiting IllegalStateException if the future isn’t in the matching state
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutionException;

public class ResultMethods {
    public static void main(String[] args) {
        CompletableFuture<String> manual = new CompletableFuture<>();
        System.out.println(manual.getNow("not yet"));
        System.out.println(manual.complete("done"));
        System.out.println(manual.complete("second time"));
        System.out.println(manual.join());

        CompletableFuture<Integer> failed = CompletableFuture.supplyAsync(() -> 10 / 0);
        try {
            failed.join();
        } catch (CompletionException e) {
            System.out.println("join(): " + e.getClass().getSimpleName() + ", cause: " + e.getCause());
        }
        try {
            failed.get();
        } catch (ExecutionException e) {
            System.out.println("get(): " + e.getClass().getSimpleName() + ", cause: " + e.getCause());
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
not yet
true
false
done
join(): CompletionException, cause: java.lang.ArithmeticException: / by zero
get(): ExecutionException, cause: java.lang.ArithmeticException: / by zero

The second complete() returned false: a future completes exactly once, and every later attempt is ignored. That’s the basis of the “first one wins” trick: several sources call complete() on the same future, and only the fastest gets its value in. The same new CompletableFuture<>(), with no pool at all, is how you turn a callback API into a future (see the FAQ).

The name join() matches Thread.join(), but it waits for a result, not a thread: the task may have finished long ago, and the pool thread may already be busy with other work.

thenApply vs thenCompose vs thenCombine: Chaining Stages

A chain is built from CompletionStage methods: thenApply transforms the result (like map on a stream), thenAccept consumes it, thenRun just runs an action, thenCompose starts the next async operation that depends on the result (like flatMap), and thenCombine merges the results of two independent tasks. Each method returns a new CompletableFuture and doesn’t block the calling thread.

Method Function Result When to use
thenApply(fn) T -> U CompletableFuture<U> Transform the value: parse, compute, format
thenAccept(consumer) T -> void CompletableFuture<Void> Use the result at the end of the chain: print it, save it
thenRun(action) () -> void CompletableFuture<Void> Do something after the stage when the result isn’t needed
thenCompose(fn) T -> CompletionStage<U> CompletableFuture<U> (no nesting) The next step is async itself and depends on the result: load a user’s orders by user id
thenCombine(other, fn) (T, U) -> V CompletableFuture<V> Two independent tasks run in parallel, you need a combined result
applyToEither(other, fn), acceptEither(other, consumer) T -> U / T -> void From whichever of the two completes first Two sources of the same data: take the faster one

A CompletableFuture example with all three: the total of a user’s orders, converted from pounds to dollars. The user is loaded by id, the orders only after that (a dependency, so thenCompose), while the exchange rate depends on neither and loads in parallel (thenCombine).

import java.util.List;
import java.util.concurrent.CompletableFuture;

public class OrderTotalExample {
    record User(long id, String name) {}
    record Order(long id, double amountGbp) {}

    static CompletableFuture<User> loadUser(long id) {
        return CompletableFuture.supplyAsync(() -> {
            pause(300);
            return new User(id, "Anna");
        });
    }

    static CompletableFuture<List<Order>> loadOrders(User user) {
        return CompletableFuture.supplyAsync(() -> {
            pause(300);
            return List.of(new Order(1, 40.0), new Order(2, 60.0));
        });
    }

    static CompletableFuture<Double> loadGbpUsdRate() {
        return CompletableFuture.supplyAsync(() -> {
            pause(400);
            return 1.25;
        });
    }

    public static void main(String[] args) {
        long start = System.nanoTime();

        CompletableFuture<Double> totalGbp = loadUser(42)
                .thenCompose(OrderTotalExample::loadOrders)          // User -> CompletableFuture<List<Order>>
                .thenApply(orders -> orders.stream().mapToDouble(Order::amountGbp).sum());

        CompletableFuture<String> report = totalGbp
                .thenCombine(loadGbpUsdRate(), (gbp, rate) -> gbp * rate) // the rate loads in parallel
                .thenApply(usd -> "Total: " + usd + " USD");

        System.out.println(report.join());
        System.out.println("Time: " + (System.nanoTime() - start) / 1_000_000 + " ms");
    }

    static void pause(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
Total: 125.0 USD
Time: 615 ms

The first line is the same on every run; the time is around 600 ms and varies a little. Sequential code would take 1000 ms: 300 for the user, 300 for the orders and 400 for the rate. Here the rate loads while the first two steps are running, so the total time is set by the longest branch.

The most common mistake in code like this is thenApply instead of thenCompose. loadOrders already returns a future, so loadUser(42).thenApply(OrderTotalExample::loadOrders) has the type CompletableFuture<CompletableFuture<List<Order>>>, and every later stage has to deal with a future inside a future. The thenApply vs thenCompose rule is the same as map vs flatMap on streams and Optional: if the function returns a plain value, use thenApply; if it returns a CompletionStage, use thenCompose.

Data passes between stages safely: everything a stage did before completing is visible to the next stage and to the code that got the result through join() or get(), with no volatile or synchronized. That’s a memory guarantee of the java.util.concurrent classes (happens-before is explained in volatile in Java). The guarantee covers the “stage → dependent stage” path only. If several parallel tasks write to one shared field, that field needs its own protection — see Thread Safety in Java.

thenApply vs thenApplyAsync: Which Thread Runs a Stage

A stage without the Async suffix (thenApply, thenAccept, thenRun…) runs in the thread that completed the previous stage, or, if the previous stage is already complete when you attach it, immediately in the thread that called thenApply. The Async variant always sends the stage to a pool: to commonPool, or to the Executor passed as the second argument.

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class WhichThread {
    public static void main(String[] args) {
        CompletableFuture.completedFuture("done")
                .thenRun(() -> print("thenRun on a completed stage"));

        try (ExecutorService io = Executors.newFixedThreadPool(2)) {
            CompletableFuture<String> slow = CompletableFuture.supplyAsync(() -> {
                pause(200);
                return "data";
            });
            CompletableFuture<Void> a = slow.thenRun(() -> print("thenRun after supplyAsync"));
            CompletableFuture<Void> b = slow.thenRunAsync(() -> print("thenRunAsync"));
            CompletableFuture<Void> c = slow.thenRunAsync(() -> print("thenRunAsync(io)"), io);
            CompletableFuture.allOf(a, b, c).join();
        }
    }

    static void print(String stage) {
        System.out.println(stage + " -> " + Thread.currentThread().getName());
    }

    static void pause(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

One possible output:

thenRun on a completed stage -> main
thenRunAsync(io) -> pool-1-thread-1
thenRunAsync -> ForkJoinPool.commonPool-worker-2
thenRun after supplyAsync -> ForkJoinPool.commonPool-worker-1

Only the first line is guaranteed: the completedFuture stage is already complete, so thenRun runs right in main. The order of the other three lines and the commonPool-worker-N numbers change from run to run; on a machine with 1–2 cores you’ll see names like Thread-0 instead (see the section on starting tasks). What doesn’t change: thenRun after supplyAsync runs in whichever thread completed slow, and thenRunAsync(…, io) runs in a thread of the io pool. How to get the current thread’s name is shown in Thread.currentThread() and the Java Main Thread.

The practical takeaway: write short transformations (thenApply(String::trim)) without Async, since handing them to a pool costs more than the operation itself. A heavy or blocking stage without Async, though, can end up somewhere unexpected: in a commonPool thread, in a thread of your I/O pool, or even in the calling thread — say, the thread handling an HTTP request. For such stages use thenApplyAsync(fn, executor) with an explicit pool.

CompletableFuture allOf and anyOf: Combining Many Tasks

CompletableFuture.allOf(cfs...) returns a CompletableFuture<Void> that completes when all the given futures have completed; it doesn’t collect their results — you take them with join() on each future, which by then is already done. anyOf(cfs...) completes together with the first future to complete and returns a CompletableFuture<Object>.

Example: ask three stores for a price in parallel, then separately find out which one answers fastest.

import java.util.Comparator;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class PriceAggregator {
    record Price(String shop, int usd) {}

    static final Map<String, Integer> DELAY_MS = Map.of("Store A", 300, "Store B", 100, "Store C", 200);
    static final Map<String, Integer> PRICE = Map.of("Store A", 1990, "Store B", 2150, "Store C", 1870);

    static Price fetchPrice(String shop) {
        pause(DELAY_MS.get(shop));                       // simulates an HTTP request
        return new Price(shop, PRICE.get(shop));
    }

    public static void main(String[] args) {
        List<String> shops = List.of("Store A", "Store B", "Store C");

        try (ExecutorService pool = Executors.newFixedThreadPool(shops.size())) {
            long start = System.nanoTime();
            List<CompletableFuture<Price>> requests = shops.stream()
                    .map(shop -> CompletableFuture.supplyAsync(() -> fetchPrice(shop), pool))
                    .toList();

            CompletableFuture<Void> all = CompletableFuture.allOf(requests.toArray(new CompletableFuture[0]));
            List<Price> prices = all
                    .thenApply(v -> requests.stream().map(CompletableFuture::join).toList())
                    .join();

            prices.forEach(p -> System.out.println(p.shop() + ": " + p.usd()));
            Price best = prices.stream().min(Comparator.comparingInt(Price::usd)).orElseThrow();
            System.out.println("Cheapest: " + best.shop());
            System.out.println("Time: " + (System.nanoTime() - start) / 1_000_000 + " ms");

            Object first = CompletableFuture.anyOf(shops.stream()
                    .map(shop -> CompletableFuture.supplyAsync(() -> fetchPrice(shop), pool))
                    .toArray(CompletableFuture[]::new)).join();
            System.out.println("First to respond: " + ((Price) first).shop());
        }
    }

    static void pause(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
Store A: 1990
Store B: 2150
Store C: 1870
Cheapest: Store C
Time: 305 ms
First to respond: Store B

The time varies by a few milliseconds; every other line is stable. Prices come out in the order of the shops list, not in the order the answers arrived: requests.stream().map(CompletableFuture::join) walks the futures in list order, and the join() inside thenApply no longer waits, because allOf guarantees they’re all done. The total is about 300 ms — the slowest store — rather than 600 ms for all three added up.

These methods have quirks the signature doesn’t tell you about:

  • An error in allOf. If even one future completes exceptionally, allOf completes exceptionally too — but only after all the others have finished. There’s no fast “fail on the first error”. How to collect the successful results when some tasks fail is in the FAQ.
  • anyOf doesn’t cancel the rest. After “Store B” answers, the other two requests keep running, and the pool’s close() at the end of the block waits for them. That’s the difference from invokeAny(), which cancels the remaining tasks (see invokeAll() and invokeAny()).
  • anyOf loses the type. The result is an Object and needs a cast. For two futures, the type-safe alternative is applyToEither.

The best way to collect results is the one in the example: return them from the stages. If each task instead calls results.add(price) on a shared ArrayList, elements will go missing, because the tasks run in different threads. In that case you need a thread-safe collection — see Concurrent Collections in Java.

CompletableFuture Exception Handling: exceptionally, handle, whenComplete

An exception in a CompletableFuture stage isn’t thrown to the caller; it’s stored in the future and passed down the chain, and every subsequent thenApply/thenAccept is skipped until a handler shows up. exceptionally replaces the error with a fallback value, handle receives both the result and the exception and returns a new value, and whenComplete only observes without changing the result.

Method Called Sees the exception Changes the result
exceptionally(ex -> value) Only on error Yes Yes: the error is replaced by a value; on success the result passes through unchanged
handle((value, ex) -> newValue) Always Yes (on success ex == null) Yes: returns a new value, the type can change
whenComplete((value, ex) -> …) Always Yes No: the future completes with the same result or the same error — good for logging and metrics
exceptionallyCompose(ex -> stage) Only on error (Java 12) Yes Yes: on error starts another async stage, for example a call to a fallback service

The tricky part is which object actually reaches the handler. What does this code print?

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;

public class ErrorHandling {
    public static void main(String[] args) {
        CompletableFuture<Integer> failing = CompletableFuture.supplyAsync(() -> {
            throw new IllegalStateException("service unavailable");
        });

        String a = failing.thenApply(n -> "result " + n)     // skipped
                .exceptionally(ex -> "exceptionally: " + ex)
                .join();
        System.out.println(a);

        String b = failing.handle((value, ex) ->
                ex == null ? "value " + value : "handle: " + ex.getCause().getMessage()).join();
        System.out.println(b);

        CompletableFuture<Integer> logged = failing.whenComplete((value, ex) ->
                System.out.println("whenComplete sees: " + ex.getCause().getMessage()));
        try {
            logged.join();
        } catch (CompletionException e) {
            System.out.println("error still there: " + e.getCause().getMessage());
        }

        CompletableFuture<Integer> manual = new CompletableFuture<>();
        manual.completeExceptionally(new IllegalStateException("directly"));
        manual.exceptionally(ex -> {
            System.out.println("completeExceptionally: " + ex);
            return 0;
        }).join();
    }
}
exceptionally: java.util.concurrent.CompletionException: java.lang.IllegalStateException: service unavailable
handle: service unavailable
whenComplete sees: service unavailable
error still there: service unavailable
completeExceptionally: java.lang.IllegalStateException: directly

An exception thrown inside supplyAsync or any stage gets wrapped by CompletableFuture in a CompletionException, and the future itself stores it that way, so every handler receives the wrapper — one attached directly to supplyAsync as well as handlers on later stages — hence ex.getCause() in handle and whenComplete. But if you complete a future by hand with completeExceptionally(), a handler attached directly to it receives the original exception, unwrapped. So code like if (ex instanceof IllegalStateException) works in one case and silently fails in the other.

Unwrap CompletionException before checking the type

Before any instanceof in a handler, get the original cause: Throwable cause = (ex instanceof CompletionException && ex.getCause() != null) ? ex.getCause() : ex; This check behaves the same for errors from supplyAsync and for completeExceptionally().

Where the handler sits in the chain matters. An exceptionally at the end catches an error from any earlier stage, while one placed after the first step protects only that step — the following stages receive the fallback value and carry on. A handler in the middle of a chain means “keep going as if everything were fine”, and that should be a deliberate decision.

Timeouts and Cancellation: orTimeout, completeOnTimeout, cancel

Since Java 9 you can put a timeout on the future itself: orTimeout(timeout, unit) completes it with a TimeoutException if the result isn’t ready in time, and completeOnTimeout(value, timeout, unit) completes it with a fallback value. Both modify and return the same future, but neither stops the task. cancel(true) doesn’t interrupt a running task either: in CompletableFuture the mayInterruptIfRunning parameter has no effect.

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class TimeoutAndCancel {
    public static void main(String[] args) {
        try (ExecutorService pool = Executors.newFixedThreadPool(3)) {
            String answer = CompletableFuture.supplyAsync(() -> slowService(2_000), pool)
                    .completeOnTimeout("cached value", 500, TimeUnit.MILLISECONDS)
                    .join();
            System.out.println(answer);

            CompletableFuture<String> strict = CompletableFuture.supplyAsync(() -> slowService(2_000), pool)
                    .orTimeout(500, TimeUnit.MILLISECONDS);
            try {
                strict.join();
            } catch (CompletionException e) {
                System.out.println("orTimeout: " + e.getCause());
            }

            CompletableFuture<Void> job = CompletableFuture.runAsync(() -> {
                pause(1_000);
                System.out.println("Task finished anyway, interrupted = " + Thread.currentThread().isInterrupted());
            }, pool);
            pause(100);
            System.out.println("cancel(true) = " + job.cancel(true));
            System.out.println("isCancelled = " + job.isCancelled());
        }   // close() waits for every pool task, including the "cancelled" one
    }

    static String slowService(long millis) {
        pause(millis);
        return "service response";
    }

    static void pause(long millis) {
        try {
            Thread.sleep(millis);
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}
cached value
orTimeout: java.util.concurrent.TimeoutException
cancel(true) = true
isCancelled = true
Task finished anyway, interrupted = false

The last line is the key difference from the Future returned by submit(): there, cancel(true) calls interrupt() on the task’s thread, and Thread.sleep() would stop right away (see Future: get(), Timeouts and Cancelling a Task). A CompletableFuture doesn’t know which thread runs its task, so cancel() only completes the future with a CancellationException: join() throws it, and dependent stages get a CompletionException with the CancellationException inside. The task itself runs to the end, and its result is thrown away.

Timeouts work the same way: the “cached value” arrived after 500 ms, but slowService slept its full two seconds and held a pool thread the whole time. That’s exactly why the example uses its own pool: in commonPool on a machine with few cores, the sleeping tasks would take every thread and job wouldn’t start on time. If the work really has to stop, the task must check a flag itself — for example, future.isCancelled() or your own AtomicBoolean.

Where Developers Get Tripped Up

Most CompletableFuture mistakes produce neither an exception nor a compiler warning: a task gets lost, a pool clogs up, or an error vanishes. Here are the usual ones, with symptoms and fixes.

Mistake What happens How to fix it
No join() at the end of main or a test The task in commonPool doesn’t get to run: daemon threads don’t keep the JVM alive Wait for the final future: join(), allOf(...).join(); in tests, always
Blocking I/O in supplyAsync without your own pool commonPool threads (cores minus one) sit waiting, parallel streams and other async tasks stall Pass a separate Executor as the second argument
thenApply instead of thenCompose Type CompletableFuture<CompletableFuture<T>>; later stages work with a future instead of the data If the function returns a CompletionStage, use thenCompose
A chain with no handler and no join() The exception sits in a future nobody reads: the logs are empty, just like submit() without get() (explained here) End the chain with exceptionally or whenComplete that logs the error
join() inside a stage that waits for a task in the same bounded pool All pool threads wait for each other and the program hangs — thread starvation (thread pool lesson FAQ; a classic deadlock is covered in Deadlock in Java) Don’t block inside stages; link tasks with thenCompose/thenCombine
supplyAsync(task).join() on the very next line The code stays synchronous, just with an extra hand-off to another thread Start all independent tasks first, then wait once at the end

The last row shows up more often than you’d expect: a loop where every iteration does supplyAsync(...).join() runs the requests strictly one after another. You only get parallelism when all the futures are created first and join() comes afterwards, as in PriceAggregator above.

CompletableFuture and Virtual Threads (Java 21)

In Java 21, tasks that mostly wait on the network or the disk can run CompletableFuture stages on virtual threads: supplyAsync(task, executor) with Executors.newVirtualThreadPerTaskExecutor(). Each task gets its own cheap thread, so a blocking call inside it doesn’t tie up a platform thread, and there’s no pool size to tune.

try (ExecutorService executor = Executors.newVirtualThreadPerTaskExecutor()) {
    List<CompletableFuture<String>> pages = urls.stream()
            .map(url -> CompletableFuture.supplyAsync(() -> download(url), executor))
            .toList();
    CompletableFuture.allOf(pages.toArray(new CompletableFuture[0])).join();
}

Virtual threads are daemons too, so the rule from the start of the lesson still applies: without join() or close() the program can end before its tasks do. What virtual threads are and how they differ from platform threads is covered in Platform and Virtual Threads; a dedicated lesson on them is planned. With virtual threads, many teams go back to plain blocking code inside each task and keep CompletableFuture for the places that genuinely need chains, combined results and in-flight error handling.

Frequently Asked Questions

How do I turn a callback-based API into a CompletableFuture?

Create an empty new CompletableFuture<T>(), call future.complete(result) in the success callback and future.completeExceptionally(error) in the error callback, then return the future to the caller. No thread pool is needed: the future is completed by whatever thread the library uses to invoke the callback. From there you attach thenApply, exceptionally and the other stages as with any other future.

Parallel stream or CompletableFuture: which should I use?

For computations over a collection (CPU-bound work), a parallel stream is simpler: list.parallelStream().map(...). For independent operations that wait (HTTP, database), use CompletableFuture with your own Executor: a parallel stream runs in ForkJoinPool.commonPool(), which has as many threads as cores minus one. By default both share that pool, so blocking tasks in one slow down the other.

How do I get the results of allOf when some tasks fail?

Handle the error in each future before passing it to allOf: requests.stream().map(f -> f.handle((v, ex) -> ex == null ? v : null)). Then allOf always completes normally, and failed tasks show up in the list as null (or a fallback value). Without this, allOf completes with a CompletionException and join() on it throws, even though the successful results are still available through getNow() on each future. The allOf example is in allOf and anyOf.

Do I need to shut down commonPool after using CompletableFuture?

No. ForkJoinPool.commonPool() lives as long as the JVM, and its shutdown() and close() have no effect. You only close your own pools that you passed to supplyAsync or thenApplyAsync, usually with try-with-resources (see Shutting Down a Pool). CompletableFuture objects themselves don’t need closing.

Comments

Please log in or register to have a possibility to add comment.