编程语言
首页 > 编程语言> > java-ScheduledExecutorService并取消行为

java-ScheduledExecutorService并取消行为

作者:互联网

我正在为此寻找令人满意的答案:

是什么导致ScheduledFuture#cancel(false)返回false?本质上,我正在创建一个新的调度程序,如下所示:

ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(1);
ScheduledFuture<?> schedulerStatus = scheduler.scheduleWithFixedDelay(this, 0L, 1L, TimeUnit.SECONDS);

在run方法中,我有如下内容:

public void run() {
    // Do some logic
    schedulerStatus.cancel(false);
}

我看过JavaDoc,但实际上并没有说什么有帮助的,

“or could not be cancelled for some other reason”

因此,任何有助于理解此处实际发生情况的帮助都将非常有用!

谢谢

更新

为了进一步扩展我上面的示例:

private final ScheduledExecutorService scheduler;
private volatile ScheduledFuture<?> schedulerStatus;

@Inject
public IndexChangeManagerImpl(IndexChangeMonitor monitor, IndexChangeObservable observable) {
    this.monitor = monitor;
    scheduler = Executors.newScheduledThreadPool(1);
}

@Override
public  void init() {
    if (schedulerStatus == null || schedulerStatus.isDone()) {
        // Kick of the scheduler to attempt to initiate the listener every second.
        schedulerStatus = scheduler.scheduleWithFixedDelay(this, 0L, 1L, TimeUnit.SECONDS);
    }
}

@Override
public void run() {
    try {
        // Before starting the monitor, ensure it is not currently running.
        monitor.shutdown();

        // Initiate the monitor.
        monitor.start();

        // Listener has been established, no more attempts necessary.
        schedulerStatus.cancel(false);

        lastLog = 0;
    } catch (ChangeMonitorException sfE) {
        long now = System.currentTimeMillis();

        if (lastLog == 0 || now - lastLog > 60000) {
            // Log every 60 seconds.
            DEBUG.error("Error attempting to initiate index change monitor.", sfE);
            lastLog = now;
        }
    }
}

希望此代码段演示了取消返回false的两个原因实际上是不可能的(注意这都是单线程的).由于在单个预定线程中调用了取消,因此任务显然既没有完成,也不能被取消.

要注意的一件事是,取消返回false是断断续续的,并且在系统处于负载状态时发生.

还有其他想法吗?

解决方法:

如果它已经执行完毕或已被取消,则看起来它返回false.

从源代码获取Java的默认Executor实现所使用的默认Future实现:

boolean innerCancel(boolean mayInterruptIfRunning) {
    for (;;) {
        int s = getState();
        if (ranOrCancelled(s))
            return false;
        if (compareAndSetState(s, CANCELLED))
            break;
    }
    if (mayInterruptIfRunning) {
        Thread r = runner;
        if (r != null)
            r.interrupt();
    }
    releaseShared(0);
    done();
    return true;
}

标签:multithreading,concurrency,scheduled-tasks,java
来源: https://codeday.me/bug/20191122/2060715.html