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:
- Prevent future execution: If the task hasn't started yet (still queued), it's removed from the queue and never runs.
- Stop running tasks: If
mayInterruptIfRunningistrueand 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 runningcancel(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.