Sub topic 11
Completing Futures Manually
This chapter assumes you know Java 8 lambdas, basic threads and ExecutorService, the functional interfaces Supplier and Consumer, and how checked and unchecked exceptions differ. It also assumes you have seen thenApply, thenAccept, join, and the exception wrapping covered in earlier chapters.
Why complete a future by hand
So far, every future came from supplyAsync or runAsync. Those methods start a task and complete the future for you when the task ends. Sometimes no such task exists. The result may arrive through an old callback API, a message from a queue, an event handler, or a response on a network connection. In those cases you create an empty CompletableFuture and complete it yourself when the result is known.
A manually created future works like a promise. The code that produces the value holds the write side. The code that consumes the value attaches stages such as thenApply and thenAccept.
The completion methods
The no-argument constructor creates an incomplete future. Three methods move it to a final state.
| Method | Effect | Returns |
|---|---|---|
| `complete(T value)` | Completes normally with the value | `true` if this call completed the future |
| `completeExceptionally(Throwable ex)` | Completes with a failure | `true` if this call completed the future |
| `cancel(boolean mayInterrupt)` | Completes with a `CancellationException` | `true` if the future is now cancelled |
A future completes at most once. The first call wins, and every later call returns false and changes nothing. This makes it safe for several threads to race to complete the same future, and it is the basis of patterns such as "first response wins".
import java.util.concurrent.CompletableFuture;
public class FirstWins {
public static void main(String[] args) {
CompletableFuture<String> f = new CompletableFuture<>();
boolean a = f.complete("first");
boolean b = f.complete("second");
boolean c = f.completeExceptionally(new RuntimeException("late"));
System.out.println(a + " " + b + " " + c + " " + f.join());
}
}This prints true false false first. The second value and the late exception are silently ignored. Check the return value when you need to know whether your call was the one that took effect.
State of a manually completed future
A future is in exactly one of three terminal states after it leaves the incomplete state. The states are normal completion, exceptional completion, and cancellation. Cancellation is a special case of exceptional completion.
You can inspect the state without blocking:
isDone()istruein all three terminal states.isCompletedExceptionally()istruefor both failure and cancellation.isCancelled()istrueonly after cancellation.getNow(T fallback)returns the value if the future is complete and the fallback otherwise. It throws if the future failed.
Java 19 added state() and resultNow() through the Future interface. They give a typed view of the same information, but you can only use them on Java 19 or later.
Bridging a callback API
The most common use of manual completion is to wrap an API that reports its result through callbacks. You create the future, hand a callback to the old API, and complete the future from inside the callback.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class Bridge {
interface Callback {
void onSuccess(String value);
void onError(Exception error);
}
static void legacyFetch(String key, Callback cb) {
new Thread(() -> {
if (key.isEmpty()) {
cb.onError(new IllegalArgumentException("empty key"));
} else {
cb.onSuccess("value-for-" + key);
}
}).start();
}
static CompletableFuture<String> fetch(String key) {
CompletableFuture<String> future = new CompletableFuture<>();
legacyFetch(key, new Callback() {
public void onSuccess(String value) {
future.complete(value);
}
public void onError(Exception error) {
future.completeExceptionally(error);
}
});
return future;
}
public static void main(String[] args) {
System.out.println(fetch("a").join());
try {
fetch("").join();
} catch (CompletionException e) {
System.out.println("failed: " + e.getCause());
}
}
}The output is value-for-a and then failed: java.lang.IllegalArgumentException: empty key. Both callbacks complete the future, so a caller never waits on a result that will not arrive. completeExceptionally stores the original exception. join then wraps it in a CompletionException, so you read the original through getCause().
The wrapper method returns the future, not the callback, and callers never see the callback. They compose the result with thenApply, thenCompose, or handle like any other future.
Which thread runs the dependent stages
A stage attached with a non-Async method such as thenAccept runs on the thread that completes the future, if the future is still incomplete when you attach the stage. If the future is already complete at attachment time, the stage runs immediately on the thread that attaches it.
import java.util.concurrent.CompletableFuture;
public class WhichThread {
public static void main(String[] args) throws InterruptedException {
CompletableFuture<String> f = new CompletableFuture<>();
f.thenAccept(v -> System.out.println(
"dependent ran on " + Thread.currentThread().getName()));
Thread completer = new Thread(() -> f.complete("x"), "completer");
completer.start();
completer.join();
}
}This prints dependent ran on completer. The consequence matters in production. If your callback thread is a network event loop or a shared I/O thread, every dependent stage you attached runs on it, and slow work in those stages blocks it. Use the Async variants, which you met in an earlier chapter, to move that work to an executor. Calling thenApplyAsync before the future completes does this in one step.
completeAsync: letting an executor do the completing
Java 9 added completeAsync. It runs a Supplier on an executor and uses the result to complete the future. It returns the same future, so you can chain it.
import java.util.concurrent.CompletableFuture;
public class CompleteAsyncDemo {
public static void main(String[] args) {
CompletableFuture<String> f = new CompletableFuture<String>()
.completeAsync(() -> "computed");
System.out.println(f.join());
}
}The one-argument form uses the default async executor, which is the common pool unless it has too few threads. The two-argument form takes an Executor. If the supplier throws, the future completes exceptionally. This is close to supplyAsync, but it lets you create the future first, hand it to other code, and decide later how and where to complete it.
Failed and already-completed futures
Two factory methods create futures that are complete from the start:
CompletableFuture.completedFuture(value)gives a successfully completed future. It is useful in tests and for returning a cached value from a method that returns a future.CompletableFuture.failedFuture(ex)(Java 9 and later) gives a future that has already failed. Return it instead of throwing from a method whose contract is to return a future. Callers then handle every failure through the future and need no separatetryblock.
Cancellation does not stop work
cancel on a CompletableFuture completes the future with a CancellationException. The boolean argument has no effect. The class does not keep a reference to the thread that runs the task, so it has nothing to interrupt.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
public class CancelDemo {
public static void main(String[] args) {
CompletableFuture<String> f = new CompletableFuture<>();
CompletableFuture<String> dependent = f.thenApply(String::toUpperCase);
f.cancel(true);
System.out.println(f.isCancelled() + " " + f.isCompletedExceptionally());
System.out.println(dependent.isCancelled());
try {
dependent.join();
} catch (CompletionException e) {
System.out.println(e.getCause().getClass().getSimpleName());
}
}
}The output is:
true true
false
CancellationExceptionThe cancelled future reports isCancelled(). Its dependent stage only fails, with a CompletionException that wraps the CancellationException, so dependent.isCancelled() is false. Stages do not propagate cancellation backwards either. If f came from supplyAsync, the supplier keeps running after f.cancel(true), and its result is discarded.
Never leave a future incomplete
If code that should complete a future throws, returns early, or is never called, the future stays incomplete forever. A join or get on it then blocks its thread forever, and the stages attached to it never run. Two habits prevent this:
- Complete the future on every path. Use
try/catcharound the producing code and callcompleteExceptionallyin thecatchblock. - Add a timeout so that a missing completion becomes a failure you can see.
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CompletionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
public class NeverCompleted {
public static void main(String[] args) {
CompletableFuture<String> f = new CompletableFuture<String>()
.orTimeout(200, TimeUnit.MILLISECONDS);
try {
f.join();
} catch (CompletionException e) {
System.out.println(e.getCause() instanceof TimeoutException);
}
}
}This prints true after about 200 milliseconds. Without orTimeout, the program would hang.
Overwriting a completed future
obtrudeValue(T) and obtrudeException(Throwable) replace the result of a future even if it is already complete. They exist for rare recovery cases. Stages that have already run keep the old result, and stages attached later see the new one, so different consumers can observe different values. Avoid them in normal code, and use complete and completeExceptionally instead.
Exposing a read-only view
A future you return to callers can be completed by those callers, because complete is a public method. If you do not want that, return a view that has no completion methods:
copy()returns a new future that completes with the result of the original. Completing the copy does not affect the original.minimalCompletionStage()returns aCompletionStagethat supports composition but throwsUnsupportedOperationExceptionfromtoCompletableFuture().
Both calls are cheap, so use them at API boundaries where outside code should consume the result and nothing else.
Exercise
Thread A calls f.complete("a") and thread B calls f.completeExceptionally(ex) on the same new CompletableFuture at nearly the same moment. What can the two callers observe, and how does each caller know whether its call took effect?
Show answer
Exactly one call wins, and which one depends on timing. The winner's call returns true and the future holds that outcome permanently, either the value "a" or the exception. The other call returns false and has no effect. Each caller learns whether it took effect from the boolean return value.
Exercise
You wrap a callback API with a manually created future. The library calls your onSuccess callback on its single I/O thread. Your callers attach thenApply stages that parse large JSON documents. What problem can this cause, and how do you fix it?
Show answer
Non-Async stages attached before completion run on the thread that completes the future, so the parsing runs on the library's I/O thread and blocks it from handling other events. Fix it by attaching thenApplyAsync with an executor you control, or by completing the future from an executor, for example by calling executor.execute(() -> future.complete(value)) inside the callback.
Exercise
A task started with supplyAsync is slow. You call future.cancel(true) and the task keeps running. Why, and what does the future report?
Show answer
CompletableFuture does not hold a reference to the thread running the task, so cancel(true) cannot interrupt it. The future completes with a CancellationException, and isCancelled() and isCompletedExceptionally() both return true, but the supplier runs to the end and its result is discarded. To stop the work, the task itself must check a flag or token.