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

后端 未结 3 1375
甜味超标
甜味超标 2021-02-12 13:54

From java docs on Future.cancel()

boolean cancel(boolean mayInterruptIfRunning)

Attempts to cancel execution of this task. This

3条回答
  •  暗喜
    暗喜 (楼主)
    2021-02-12 14:32

    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

提交回复
热议问题