CKTIS / Java
Future.isDone(): completion is not success
`Future.isDone()` checks whether a task is complete without waiting for it. It returns `true` even when the task threw an exception or was cancelled.
Version: Java SE 21
Syntax
boolean isDone()
// Call on a java.util.concurrent.Future<V> instance:
boolean done = future.isDone();Future.isDone is a no-argument instance method on the java.util.concurrent.Future<V> interface. Calling future.isDone() returns a boolean without waiting for the task to finish. false means the task was not done when checked: it might not have started yet, or it might still be running.
true covers normal completion, completion with an exception, and cancellation. The value alone does not distinguish these outcomes or tell you that a result is available. Cancellation also does not prove that the task code has stopped running.
In Java SE 21, future.state() distinguishes SUCCESS, FAILED, CANCELLED, and RUNNING. future.get() waits if needed: it returns the result after normal completion, throws ExecutionException with the task exception as its cause, or throws CancellationException if cancelled. If the calling thread is interrupted while waiting, it throws InterruptedException.
Examples
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;
public class Main {
public static void main(String[] args) throws InterruptedException {
FutureTask<Integer> task = new FutureTask<>(() -> {
throw new IllegalStateException("calculation failed");
});
Future<Integer> future = task;
System.out.println("Before run: " + future.isDone());
task.run();
System.out.println("After run: " + future.isDone());
try {
future.get();
} catch (ExecutionException e) {
System.out.println("Cause: " + e.getCause().getClass().getSimpleName());
}
}
}Result
Before run: false After run: true Cause: IllegalStateException
Calling `task.run()` directly runs the task on the current thread. `isDone()` is `false` before the call and `true` afterward, even though `get()` throws an `ExecutionException` caused by `IllegalStateException`.
Related lessons
- Java · Lesson 50 · Intermediate · Version: 2