Tom Tom - 2 years ago 122
Java Question

What does Future.cancel() do if not interrupting?

From java docs on Future.cancel()

boolean cancel(boolean mayInterruptIfRunning)

Attempts to cancel execution of this task. This attempt will fail if the task has already completed, has already been cancelled, or could not be cancelled for some other reason. If successful, and this task has not started when cancel is called, this task should never run. If the task has already started, then the mayInterruptIfRunning parameter determines whether the thread executing this task should be interrupted in an attempt to stop the task.

My question is what does cancel do if mayInterruptIfRunning is false?

how does it cancel or stop the task from executing if it has already been run?

Answer Source

If it is not interrupting it will simply tell the future that is is cancelled. You can check that via isCancelled() but nothing happens if you don't check that manually.

Below example code shows how you could do it.

private static FutureTask<String> task = new FutureTask<String>(new Callable<String>() {

    public String call() throws Exception {
        while (!task.isCancelled()) {
        return "The End";


public static void main(String[] args) throws InterruptedException {
    new Thread(task).start();

The task is started, and after 1.5 iterations told to stop. It will continue sleeping (which it would not if you interrupted it) and then finish.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download