java - 删除 ThreadPoolExecutor 的所有排队任务

标签 java multithreading threadpool executorservice executor

我有一个关于 ThreadPoolExecutor 的相当简单的问题。 .我有以下情况:我必须使用队列中的对象,为它们创建适当的工作任务并将它们提交给 ThreadPoolExecutor。这很简单。但在关闭场景中,许多工作人员可能会排队等待执行。由于其中一个任务可能运行了一个小时,并且我希望应用程序相对快速地正常关闭,因此我想丢弃 ThreadPoolExecutor 中的所有排队任务,而已经处理的任务应该正常完成。

ThreadPoolExecutor 文档有一个 remove()方法,但只允许删除特定任务。 purge()仅适用于已取消的 future 任务。我的想法是清除包含所有排队任务的队列。 ThreadPoolExecutor 提供对此内部队列的访问,但文档指出:

Method getQueue() allows access to the work queue for purposes of monitoring and debugging. Use of this method for any other purpose is strongly discouraged.

因此,捕获这个队列并清除它不是一种选择。此外,这个文档片段说:

Two supplied methods, remove(java.lang.Runnable) and purge() are available to assist in storage reclamation when large numbers of queued tasks become cancelled.

怎么样?当然,我可以维护我提交给执行程序的所有任务的列表,并且在关闭的情况下,我遍历所有条目并使用 remove() 方法将它们从 ThreadPoolExecutor 中删除......但是......来吧,这是一个浪费内存并且维护这个列表很麻烦。 (例如删除已经执行的任务)

感谢任何提示或解决方案!

最佳答案

我曾经在一个具有长时间运行线程的应用程序上工作。我们在关机时执行此操作,

BlockingQueue<Runnable> queue = threadPool.getQueue();
List<Runnable> list = new ArrayList<Runnable>();
int tasks = queue.drainTo(list);

列表被保存到一个文件中。启动时,列表会重新添加到池中,因此我们不会丢失任何工作。

关于java - 删除 ThreadPoolExecutor 的所有排队任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1679579/

相关文章:

java - jsp中的下载链接不起作用

java - 当 ScheduledExecutorService 的任务抛出异常时,不会打印堆栈跟踪

java - 无法在 Spring 中初始化 bean 类

java - 以下代码线程安全吗?

java - Java有可索引的多队列线程池吗?

java - 如何强制执行单例(一个全局实例)ScheduledExecutorService,一次一项任务?

java - 使用 xjc 编码创建嵌套类

c++ - Qthread : worker for I/O queue

c# - 开发将使用/创建多个线程的 C# Windows 服务需要专家意见

c# - 使用阻塞集合创建文件拾取过程