如何为Executors.newScheduledThreadPool(5)设置RemoveOnCancelPolicy [英] How to setRemoveOnCancelPolicy for Executors.newScheduledThreadPool(5)
问题描述
我有这个:
ScheduledExecutorService scheduledThreadPool = Executors
.newScheduledThreadPool(5);
然后我像这样开始一个任务:
Then I start a task like so:
scheduledThreadPool.scheduleAtFixedRate(runnable, 0, seconds, TimeUnit.SECONDS);
我以这种方式保留对Future的引用:
I preserve the reference to the Future this way:
ScheduledFuture<?> scheduledFuture = scheduledThreadPool.scheduleAtFixedRate(runnable, 0, seconds, TimeUnit.SECONDS);
我希望能够取消并删除未来
scheduledFuture.cancel(true);
但是,这个SO答案指出,取消操作不会将其删除,而添加新任务将导致许多无法使用GC的任务结束.
However this SO answer notes that canceling doesn't remove it and adding new tasks will end in many tasks that can't be GCed.
https://stackoverflow.com/a/14423578/2576903
他们提到了有关setRemoveOnCancelPolicy
的内容,但是此scheduledThreadPool
没有这种方法.我该怎么办?
They mention something about setRemoveOnCancelPolicy
, however this scheduledThreadPool
doesn't have such method. What do I do?
推荐答案
此方法 .html"rel =" noreferrer> ScheduledThreadPoolExecutor .
This method is declared in 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 和类似方法.
This executor is returned by Executors class by newScheduledThreadPool and similar methods.
public static ScheduledExecutorService newScheduledThreadPool(int corePoolSize) {
return new ScheduledThreadPoolExecutor(corePoolSize);
}
因此,简而言之,您可以强制转换执行程序服务引用以调用方法
So in short, you can cast the executor service reference to call the method
ScheduledThreadPoolExecutor ex = (ScheduledThreadPoolExecutor) Executors.newScheduledThreadPool(5);
ex.setRemoveOnCancelPolicy(true);
或自己创建new ScheduledThreadPoolExecutor
.
ScheduledThreadPoolExecutor ex = new ScheduledThreadPoolExecutor(5);
ex.setRemoveOnCancelPolicy(true);
这篇关于如何为Executors.newScheduledThreadPool(5)设置RemoveOnCancelPolicy的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!