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

Cancelling In-Flight Callable Tasks

Using Future.cancel() to attempt cancellation and understanding mayInterruptIfRunning behavior.

Cancelling In-Flight Callable Tasks

What you'll learn: How to use Future.cancel() to attempt cancellation of running Callable tasks and what the mayInterruptIfRunning parameter controls.

The Cancellation Challenge

You've submitted a Callable task and received a Future, but now circumstances have changed—maybe the user clicked "cancel," or the result is no longer needed. The Future.cancel(boolean mayInterruptIfRunning) method lets you attempt to stop the task, but its behavior depends on the task's state and your choice of parameter.

The mayInterruptIfRunning Parameter

The boolean parameter determines how aggressively to cancel:

  • cancel(false): Only cancels if the task hasn't started executing yet. If it's already running, the cancellation request fails and returns false.

  • cancel(true): Cancels queued tasks and attempts to interrupt running threads via Thread.interrupt(). This sets the interrupt flag on the task's thread, but the task must actually check for interruption to cooperate.

Cancellation Is Cooperative

Think of it like asking someone to stop working: you can tap them on the shoulder (send an interrupt), but they decide whether to stop. If your Callable ignores interrupts or doesn't check Thread.interrupted(), it will continue running despite cancellation.

Important: After a successful cancellation, calling get() throws CancellationException.

What Cancel Returns

The method returns true if cancellation succeeded (task was queued or interrupted), false if the task already completed or couldn't be cancelled.

Key Takeaway: Use Future.cancel(true) to interrupt running tasks and cancel(false) to only cancel queued work, but remember cancellation requires task cooperation through interrupt checking—it's a request, not a guarantee.