如何设置DemoveOnCancelPolicy for Executors.newScheduledThreadPool(5)

2022-09-03 14:24:29

我有这个:

ScheduledExecutorService scheduledThreadPool = Executors
        .newScheduledThreadPool(5);

然后我开始了一个这样的任务:

scheduledThreadPool.scheduleAtFixedRate(runnable, 0, seconds, TimeUnit.SECONDS);

我以这种方式保留了对未来的引用:

ScheduledFuture<?> scheduledFuture = scheduledThreadPool.scheduleAtFixedRate(runnable, 0, seconds, TimeUnit.SECONDS);

我希望能够取消并移除未来

scheduledFuture.cancel(true);

但是,此SO答案指出,取消不会删除它,添加新任务将以许多无法GCed的任务结束。

https://stackoverflow.com/a/14423578/2576903

他们提到了一些关于,但是这没有这样的方法。我该怎么办?setRemoveOnCancelPolicyscheduledThreadPool


答案 1

此方法ScheduledThreadPoolExecutor 中声明。

/**
 * Sets the policy on whether cancelled tasks should be immediately
 * removed from the work queue at time of cancellation.  This value is
 * by default {@code false}.
 *
 * @param value if {@code true}, remove on cancellation, else don't
 * @see #getRemoveOnCancelPolicy
 * @since 1.7
 */
public void setRemoveOnCancelPolicy(boolean value) {
    removeOnCancel = value;
}

此执行程序由 executors 类通过 newScheduledThreadPool 和类似方法返回。

public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
    return new ScheduledThreadPoolExecutor(corePoolSize);
}

简而言之,您可以强制执行器服务引用来调用该方法

ScheduledThreadPoolExecutor ex = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5);
ex.setRemoveOnCancelPolicy(true);

或自己创建。new ScheduledThreadPoolExecutor

ScheduledThreadPoolExecutor ex = new ScheduledThreadPoolExecutor(5);
ex.setRemoveOnCancelPolicy(true);

答案 2

推荐