Course contentsShow
← Java
Lesson 2756 of 2,87050. Executor FrameworkFree lesson

Checking Callable Task Status with isDone and isCancelled

Polling Future state to determine if computation completed, was cancelled, or is still running.

Checking Callable Task Status with isDone and isCancelled

What you'll learn: How to poll a Future to determine whether your Callable task has completed, was cancelled, or is still running—without blocking your thread.

Why Poll Task State?

Sometimes you don't want to block on Future.get() until a result is ready. Instead, you want to check if the task is done, handle other work, and come back later. Think of it like checking your mailbox: you peek to see if a package arrived without waiting at the door all day.

The isDone() Method

isDone() returns true if the task has completed for any reason:

  • Normal completion (result ready)
  • Threw an exception
  • Was cancelled

It returns false if the computation is still running. This method never blocks—it returns immediately.

ExecutorService executor = Executors.newSingleThreadExecutor();
Future<Integer> future = executor.submit(() -> {
    Thread.sleep(2000);
    return 42;
});

if (future.isDone()) {
    System.out.println("Task completed");
} else {
    System.out.println("Still running..."); // Initially prints this
}

The isCancelled() Method

isCancelled() returns true only if the task was explicitly cancelled via cancel() before completing. It helps you distinguish cancellation from normal completion or exceptions.

future.cancel(true);

if (future.isCancelled()) {
    System.out.println("Task was cancelled");
} else if (future.isDone()) {
    System.out.println("Task completed normally");
}

Combining Both for Full State Awareness

Use these methods together to make informed decisions without blocking:

if (!future.isDone()) {
    // Still running, do other work
} else if (future.isCancelled()) {
    // Handle cancellation
} else {
    // Completed normally or with exception
}

Key Takeaway: isDone() and isCancelled() let you non-blockingly poll a Future's state, distinguishing between running, completed, and cancelled tasks without waiting for results.