isDone and isCancelled: Checking Completion State
What you'll learn: How to query a CompletableFuture to determine whether it has completed normally, exceptionally, or been cancelled without blocking your thread.
The Need for Non-Blocking Status Checks
When working with asynchronous computations, you often need to check whether a task has finished without actually waiting for it. CompletableFuture provides two status methods that return immediately, letting you make decisions based on current state rather than blocking execution.
The isDone Method
The isDone() method returns true if the CompletableFuture has completed in any way—whether normally, exceptionally, or by cancellation:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> {
// Long-running task
return "result";
});
if (future.isDone()) {
// Computation has finished (successfully or not)
String result = future.join();
} else {
// Still running, do something else
}
Think of isDone() as asking "Is this package delivered yet?" It doesn't tell you whether the delivery was successful or if it was sent back—just that the delivery attempt is complete.
The isCancelled Method
The isCancelled() method returns true only if the CompletableFuture was explicitly cancelled:
CompletableFuture<String> future = CompletableFuture.supplyAsync(() -> "result");
future.cancel(true);
if (future.isCancelled()) {
// Task was cancelled
System.out.println("Task cancelled");
} else if (future.isDone()) {
// Task completed normally or exceptionally
}
If isCancelled() returns true, then isDone() will also return true—cancellation is a type of completion.
Typical Usage Pattern
These methods are useful for polling scenarios, progress indicators, or deciding whether to wait for results or take an alternative path in your logic.
Key Takeaway: Use isDone() to check if a CompletableFuture has finished in any way, and isCancelled() specifically to detect cancellation—both return immediately without blocking.