Sub topic 2
Creating a CompletableFuture
This chapter covers the ways to get a CompletableFuture instance: starting background work, wrapping a value you already have, and creating an empty future that you complete yourself. It assumes you know Java 8 lambdas and method references, ExecutorService basics, the functional interfaces Supplier and Runnable, and the difference between checked and unchecked exceptions.
The creation methods at a glance
A CompletableFuture<T> is a handle to a result of type T that may not exist yet. Every future you build starts from one of five entry points.
| Method | Starts work? | Result type | Typical use |
|---|---|---|---|
| `supplyAsync(Supplier<U>)` | Yes, on the common pool | `CompletableFuture<U>` | Background work that returns a value |
| `supplyAsync(Supplier<U>, Executor)` | Yes, on your executor | `CompletableFuture<U>` | Same, with control over threads |
| `runAsync(Runnable)` and `runAsync(Runnable, Executor)` | Yes | `CompletableFuture<Void>` | Background work with no result |
| `completedFuture(U)` | No, already done | `CompletableFuture<U>` | Tests, caches, short-circuit paths |
| `failedFuture(Throwable)` (Java 9+) | No, already failed | `CompletableFuture<U>` | Returning an error from a method that returns a future |
| `new CompletableFuture<>()` | No, incomplete | `CompletableFuture<T>` | Bridging callbacks; you complete it later |
Starting work with supplyAsync and runAsync
supplyAsync takes a Supplier, runs it on another thread, and returns a future that completes with the supplier's return value. runAsync does the same for a Runnable, so its future is a CompletableFuture<Void> that completes with null.
import java.util.concurrent.CompletableFuture;
public class CreateDemo {
public static void main(String[] args) {
CompletableFuture<String> greeting = CompletableFuture.supplyAsync(() -> {
System.out.println("supplier on " + Thread.currentThread().getName());
return "hello";
});
CompletableFuture<Void> log = CompletableFuture.runAsync(() ->
System.out.println("runnable on " + Thread.currentThread().getName()));
System.out.println(greeting.join());
log.join();
}
}Typical output looks like this. The line order can vary, because the two tasks and main run concurrently.
supplier on ForkJoinPool.commonPool-worker-1
runnable on ForkJoinPool.commonPool-worker-2
helloThree properties of this code matter.
- The work is eager. The task is submitted the moment
supplyAsyncis called. Nothing waits forjoin. If you create a future and never read it, the work still runs. - The default thread is a common pool thread. Without an executor argument, the task runs on
ForkJoinPool.commonPool(). Chapter "Choosing an executor" covers when that is a bad choice. mainhas to wait, or the work can be lost. Common pool threads are daemon threads. They do not keep the JVM alive. Ifmainreturns before the task finishes, the JVM exits and the task is cut off silently. That is why the example callsjoinon both futures.
Passing your own executor
Both methods have an overload that takes an Executor as the last argument. The task then runs on that executor's threads instead of the common pool.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class CustomExecutorDemo {
public static void main(String[] args) {
ExecutorService pool = Executors.newFixedThreadPool(2);
try {
CompletableFuture<Integer> answer = CompletableFuture.supplyAsync(() -> {
System.out.println("running on " + Thread.currentThread().getName());
return 6 * 7;
}, pool);
System.out.println(answer.join());
} finally {
pool.shutdown();
}
}
}This prints running on pool-1-thread-1 and then 42. The future does not own the executor, so you must shut it down yourself. If you skip shutdown(), the non-daemon pool threads keep the JVM running after main finishes.
What the common pool does on small machines
The common pool is sized at roughly availableProcessors() - 1 threads. If that works out to fewer than 2 (a single-core container, for example), CompletableFuture does not use the common pool at all. It starts a new thread for every async task. Code that relies on the common pool's thread reuse can behave differently in a small container than on your laptop. Passing an explicit executor removes this variable.
Wrapping values you already have
Sometimes a method must return a CompletableFuture but the answer is already known. A cache hit is the classic case. completedFuture creates a future that is already finished, and no thread is involved.
import java.util.concurrent.CompletableFuture;
public class ReadyDemo {
public static void main(String[] args) {
CompletableFuture<String> ok = CompletableFuture.completedFuture("cached");
System.out.println(ok.isDone()); // true
System.out.println(ok.join()); // cached
CompletableFuture<String> bad =
CompletableFuture.failedFuture(new IllegalStateException("no data"));
System.out.println(bad.isCompletedExceptionally()); // true
try {
bad.join();
} catch (java.util.concurrent.CompletionException e) {
System.out.println(e.getCause()); // java.lang.IllegalStateException: no data
}
}
}failedFuture exists since Java 9. On Java 8 you create a new CompletableFuture<>() and call completeExceptionally on it, which does the same thing in two lines.
Stages you attach to an already-completed future run immediately, on the thread that attaches them. This is useful in unit tests, because you get deterministic behavior with no threads involved.
Creating an empty future
The no-argument constructor gives you a future that nobody is working on. It completes only when some code calls complete(value) or completeExceptionally(throwable). You use it to adapt an API that reports results through callbacks. This chapter only introduces the idea, and the chapter "Completing futures manually" treats it in full.
import java.util.concurrent.CompletableFuture;
public class EmptyDemo {
public static void main(String[] args) {
CompletableFuture<String> promise = new CompletableFuture<>();
System.out.println(promise.isDone()); // false
promise.complete("filled in");
System.out.println(promise.isDone()); // true
System.out.println(promise.join()); // filled in
System.out.println(promise.complete("second")); // false: already completed
System.out.println(promise.join()); // still: filled in
}
}A future completes at most once. Later calls to complete return false and change nothing.
Failures inside the task
A Supplier cannot declare checked exceptions, and an unchecked exception thrown inside it does not propagate to the caller of supplyAsync. The future captures it instead. The failure shows up when you read the result.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class FailureDemo {
public static void main(String[] args) {
CompletableFuture<Integer> parsed =
CompletableFuture.supplyAsync(() -> Integer.parseInt("abc"));
try {
parsed.join();
} catch (CompletionException e) {
System.out.println("wrapper: " + e.getClass().getSimpleName());
System.out.println("cause: " + e.getCause());
}
System.out.println(parsed.isCompletedExceptionally()); // true
}
}The output is:
wrapper: CompletionException
cause: java.lang.NumberFormatException: For input string: "abc"join wraps the original exception in a CompletionException. Chapter "Getting the result: join versus get" compares this with get, which throws a checked ExecutionException instead.
Checked exceptions inside lambdas
Code that throws a checked exception, such as Thread.sleep or file I/O, does not compile as a bare lambda body for Supplier. Catch the exception and rethrow it as an unchecked one. Wrapping it in CompletionException keeps the exception type the same as it would be after propagation.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class CheckedDemo {
static String slowLookup() {
try {
Thread.sleep(200);
return "found";
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
throw new CompletionException(e);
}
}
public static void main(String[] args) {
System.out.println(CompletableFuture.supplyAsync(CheckedDemo::slowLookup).join());
}
}Restoring the interrupt flag with Thread.currentThread().interrupt() before rethrowing is good practice. It lets the executor see that the thread was interrupted.
Common errors when creating futures
- Calling
jointoo early. WritingsupplyAsync(...).join()right away turns the code back into a blocking call. Create the future, attach stages, and block only at the edge of your program, if at all. - Using
runAsyncand then expecting a value. Its future has typeCompletableFuture<Void>, sojoin()returnsnull. UsesupplyAsyncwhen you need a result. - Passing
null.supplyAsync(null)andsupplyAsync(task, null)throwNullPointerExceptionimmediately, in the calling thread. This is the one failure that does not go into the future. - Blocking work in the common pool. Sleeping or waiting on I/O inside a common-pool task occupies one of very few threads. Other tasks, and parallel streams, which use the same pool, then queue behind it. Pass a dedicated executor for blocking work.
- Leaking executors. An
ExecutorServiceyou create is yours to close. Usetry/finallywithshutdown(), as in the example above. - Assuming laziness. A future from
supplyAsyncis already running. If you build one inside a method that might be called twice, both tasks start.
Summary of when to use each
Use supplyAsync when the work produces a value, and runAsync when it only has side effects. Use completedFuture and failedFuture when the outcome is known and the method signature demands a future. Use the empty constructor when the result will be delivered by someone else's callback. For any work that blocks, or that must not compete with parallel streams, pass an executor.
Exercise
A colleague writes CompletableFuture.runAsync(() -> System.out.println("done")); as the last line of main, and the program sometimes prints nothing. Why does this happen, and what are two ways to fix it?
Show answer
runAsync uses the common pool, whose threads are daemon threads, so the JVM can exit before the task runs. Fix it by keeping the returned future and calling join() (or get()) on it before main ends, or by passing a non-daemon executor, such as Executors.newFixedThreadPool(1), and waiting for the task before calling shutdown() on that executor.
Exercise
What is the type of CompletableFuture.supplyAsync(() -> 10 / 0), and what happens when you call join() on it?
Show answer
It is a CompletableFuture<Integer>. The ArithmeticException is thrown inside the supplier on a pool thread and captured by the future, not thrown from supplyAsync. join() throws a CompletionException whose getCause() is the ArithmeticException, and isCompletedExceptionally() returns true.
Exercise
You are writing a method CompletableFuture<User> findUser(String id) that checks an in-memory map first and calls a slow remote service only on a miss. Which creation methods do you use for the hit path and the miss path, and why?
Show answer
For a hit, return CompletableFuture.completedFuture(user), because the value is known and no thread is needed. For a miss, return CompletableFuture.supplyAsync(() -> remoteLookup(id), ioExecutor), passing an executor sized for blocking calls so the common pool is not occupied. Callers see the same return type in both cases.