java - 如何为Executors.newScheduledThreadPool设置RemoveOnCancelPolicy(5)

标签 java multithreading concurrency

我有这个:

ScheduledExecutorService scheduledThreadPool = Executors
        .newScheduledThreadPool(5);

然后我开始这样的任务:

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

我以这种方式保留对 Future 的引用:

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

我希望能够取消并删除 future

scheduledFuture.cancel(true);

然而,这个 SO 回答指出,取消并不会删除它,添加新任务将导致许多无法进行 GC 的任务。

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

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

最佳答案

methodScheduledThreadPoolExecutor 中声明.

/**
 * 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;
}

此执行器由 newScheduledThreadPool 的 Executors 类返回和类似的方法。

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);

关于java - 如何为Executors.newScheduledThreadPool设置RemoveOnCancelPolicy(5),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36747987/

相关文章:

c++ - 并发访问 QTcpSocket 对象

java - 有没有办法像在 ExecutorCompletionService 中那样在 spring 中轮询一组 Future 对象?

java - 了解关闭时的关闭请求标志

c# - 在 .net 中管理高/低优先级线程

c# - 防止线程不必要地执行 CoSTLy 任务

java.lang.VerifyError : Inconsistent stackmap frames

java - 如何将 @override 方法从 Activity 重写到另一个类中

java - Jquery ajax 调用没有命中 servlet

java - 更改 spring root url 名称

c - atomic_exchange_explicit/atomic_exchange 引入的内存顺序