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

cancel(): Attempting to Stop Running Tasks

Learn how cancel(mayInterruptIfRunning) attempts to cancel task execution and prevent future execution.

cancel(): Attempting to Stop Running Tasks

What you'll learn: How to use Future's cancel() method to attempt stopping tasks mid-execution or prevent them from starting.

The Power to Stop Tasks

You've learned to submit tasks and check their status—but what if you need to stop a task? Maybe a search is taking too long, or user input has made the result irrelevant. The cancel(boolean mayInterruptIfRunning) method gives you this control.

How cancel() Works

The cancel() method attempts two things:

  1. Prevent future execution: If the task hasn't started yet (still queued), it's removed from the queue and never runs.
  2. Stop running tasks: If mayInterruptIfRunning is true and the task is already executing, the thread running it receives an interrupt signal.

The boolean parameter is crucial:

  • cancel(false) — Only prevents unstarted tasks from running
  • cancel(true) — Prevents unstarted tasks and tries to interrupt running ones

Think of it like calling to cancel a pizza delivery: if it hasn't left the kitchen, cancellation succeeds easily. If the driver's already en route, you can request they turn back, but they might not respond immediately—or at all.

Important Limitations

cancel() does not forcefully stop threads. If your task ignores interrupts (doesn't check Thread.interrupted() or handle InterruptedException), calling cancel(true) has no effect. The task continues running to completion.

After cancellation, get() throws CancellationException, and isDone() returns true (cancelled tasks are "done" in the sense they won't produce results).

Key Takeaway:
cancel(mayInterruptIfRunning) attempts to prevent task execution or signal running threads to stop via interruption, but cooperative task design is required for effective mid-execution cancellation.