Sub topic 11
Completing Futures Manually
A CompletableFuture normally completes when the asynchronous operation supplied to it finishes. Sometimes, however, another part of your program already owns the result. In that case, create an empty future and complete it later with complete or completeExceptionally.
This pattern is useful for adapting callback-based APIs, coordinating events, or exposing a result that will arrive from another thread.
Creating an incomplete future
The no-argument constructor creates a future that is initially incomplete:
CompletableFuture<String> promise = new CompletableFuture<>();A CompletableFuture<T> is also a promise: an object representing a value that may become available later. The type parameter T is the type of that future value.
You can attach dependent stages before the value exists. Those stages wait until the future completes.
import java.util.concurrent.CompletableFuture;
public class Manual {
public static void main(String[] args) {
CompletableFuture<String> promise = new CompletableFuture<>();
CompletableFuture<Void> display = promise
.thenAccept(value -> System.out.println("Received: " + value));
new Thread(() -> {
try {
Thread.sleep(200);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
promise.completeExceptionally(e);
return;
}
promise.complete("done");
}).start();
display.join();
}
}The main thread creates the future and registers thenAccept. A separate thread later calls complete("done"). That call supplies the result and triggers the dependent stage.
The thread that calls complete may also run dependent actions. Therefore, keep completion code short. If a dependent action performs slow work, choose an appropriate executor with an asynchronous method such as thenAcceptAsync.
Completion succeeds only once
complete returns a boolean. It returns true when this call completes the future and false when the future was already completed.
import java.util.concurrent.CompletableFuture;
public class CompleteOnce {
public static void main(String[] args) {
CompletableFuture<Integer> result = new CompletableFuture<>();
boolean first = result.complete(10);
boolean second = result.complete(20);
System.out.println(first); // true
System.out.println(second); // false
System.out.println(result.join()); // 10
}
}The second call does not replace the first value. This rule prevents competing producers from changing a result after consumers have observed it.
Completing with a failure
Use completeExceptionally when the operation cannot produce a normal result.
import java.util.concurrent.CompletableFuture;
public class ManualFailure {
public static void main(String[] args) {
CompletableFuture<String> result = new CompletableFuture<>();
result.exceptionally(error -> {
System.out.println("Failed: " + error.getMessage());
return "fallback";
});
result.completeExceptionally(new IllegalStateException("service unavailable"));
System.out.println(result.join()); // fallback
}
}The future is completed in the exceptional state. The exceptionally stage converts that failure into the normal value "fallback".
Without a recovery stage, join throws a CompletionException. Its cause is the exception supplied to completeExceptionally. Code that catches failures should inspect the cause when it needs the original exception type.
A manual completion flow
The future moves from incomplete to exactly one terminal state: successful or exceptional.
Manual completion does not start work by itself. The constructor only creates the coordination object. Your code must arrange for another thread, callback, message handler, or event listener to call one of the completion methods.
Exercise
What value does result.join() return, and why? CompletableFuture<String> result = new CompletableFuture<>(); result.complete("first"); result.complete("second");
Show answer
It returns "first". The first successful call completes the future, and later calls return false without changing its value.