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

isCancelled(): Detecting Cancelled Tasks

Check if a task was successfully cancelled before completion using the isCancelled() method.

isCancelled(): Detecting Cancelled Tasks

You'll learn: How to use the isCancelled() method to determine if a task was successfully cancelled before it completed.

Understanding isCancelled()

After calling cancel() on a Future, you might wonder: did the cancellation actually succeed? The isCancelled() method answers this question. It returns true if the task was cancelled before completing normally, and false otherwise.

Think of it like checking whether a delivery order was successfully stopped before the package arrived. If the truck was already at your door, the cancellation failed—but if you caught it in time, it was cancelled.

How It Works

The isCancelled() method specifically tells you whether cancellation succeeded:

ExecutorService executor = Executors.newSingleThreadExecutor();

Future<String> future = executor.submit(() -> {
    Thread.sleep(5000);
    return "Done";
});

// Try to cancel immediately
boolean cancelled = future.cancel(true);

if (future.isCancelled()) {
    System.out.println("Task was successfully cancelled");
} else {
    System.out.println("Task was NOT cancelled");
}

executor.shutdown();

Key Distinctions

  • isDone() returns true for both completed AND cancelled tasks
  • isCancelled() returns true ONLY if the task was cancelled (it's more specific)
  • If a task completes normally before cancel() is called, isCancelled() returns false
  • Once isCancelled() returns true, it will always return true for that Future
// If the task finishes before cancel:
future.cancel(false);
// isCancelled() → false
// isDone() → true

// If cancel succeeds:
// isCancelled() → true
// isDone() → true (cancelled tasks are "done")

Key Takeaway:
Use isCancelled() to check if a task was successfully stopped before completion—it provides more specific information than isDone() alone, helping you understand whether cancellation actually happened.