如何为Executors.newScheduledThreadPool(5)设置RemoveOnCancelPolicy [英] How to setRemoveOnCancelPolicy for Executors.newScheduledThreadPool(5)

查看:1739
本文介绍了如何为Executors.newScheduledThreadPool(5)设置RemoveOnCancelPolicy的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆