Manual Completion with complete and completeExceptionally
You'll learn how to programmatically complete a CompletableFuture from anywhere in your code, either with a successful result or an exceptional failure.
The Core Idea
Unlike the traditional Future from a thread pool—which completes automatically when the submitted task finishes—a CompletableFuture can be manually completed by any code that holds a reference to it. This gives you explicit control over when and how the future resolves.
Think of it like a promise you can fulfill yourself: you hand someone a CompletableFuture (a "promise" of a future value), then later you decide whether to deliver the result successfully or report that something went wrong.
The Two Manual Completion Methods
complete(T value)
Completes the future successfully with the given result. Any threads blocked on get() will receive this value. If the future is already completed, this method does nothing and returns false.
CompletableFuture<String> future = new CompletableFuture<>();
// Later, from any thread or callback:
future.complete("Success!");
String result = future.get(); // returns "Success!" immediately
completeExceptionally(Throwable ex)
Completes the future with an exception. Any threads calling get() will receive an ExecutionException wrapping this throwable. Again, if already completed, this returns false.
CompletableFuture<Integer> future = new CompletableFuture<>();
future.completeExceptionally(new RuntimeException("Failed!"));
future.get(); // throws ExecutionException caused by RuntimeException
Why This Matters
Manual completion lets you bridge traditional callback-based or event-driven code with the CompletableFuture model. You can create a future, pass it around, and complete it when some external event occurs—network response, user input, or custom logic.
Key Takeaway: Use complete() to manually fulfill a CompletableFuture with a success value, and completeExceptionally() to signal failure—giving you explicit control over asynchronous result delivery.