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

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


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>() {    @Override    public String call() throws Exception {        while (!task.isCancelled()) {            System.out.println("Running...");            Thread.sleep(1000);        }        return "The End";    }});public static void main(String[] args) throws InterruptedException {    new Thread(task).start();    Thread.sleep(1500);    task.cancel(false);}

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.


nothing will be done if the task has already started and mayInterruptIfRunning is false,

below is the cancel()

public boolean cancel(boolean mayInterruptIfRunning) {    if (state != NEW)        return false;    if (mayInterruptIfRunning) {        if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, INTERRUPTING))            return false;        Thread t = runner;        if (t != null)            t.interrupt();        UNSAFE.putOrderedInt(this, stateOffset, INTERRUPTED); // final state    }    else if (!UNSAFE.compareAndSwapInt(this, stateOffset, NEW, CANCELLED))        return false;    finishCompletion();    return true;}

we can see that if mayInterruptIfRunning is false,cancel() just change state from NEW to CANCELLED and return false,nothing else will be done


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?

If the task has already started running, and mayInterruptIfRunning is false, then there is nothing to be done. In Java, interrupting a thread is considered to be the only safe way of stopping it short of completion - and even that requires the task to "comply" by checking for interruption at some implementation-specific interval.

Related: How do you kill a thread in Java?