gpt4 book ai didi

java - 清理 ThreadPoolExecutor 中的有界队列

转载 作者:行者123 更新时间:2023-11-30 04:17:13 28 4
gpt4 key购买 nike

在阅读线程池执行器的文档时,我看到如下:

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

我知道,如果任何任务被取消,我可以使用这些方法来清理工作队列。我试图了解实际源中的哪一部分会自动进行清理。假设我从 10 个队列开始,其中有 4 个任务被取消,当新任务到达时,队列大小是 6 还是只是忽略 4 个被取消的任务并重置为 10。

从来源我看到这个评论:

/**
* Tries to remove from the work queue all
* tasks that have been cancelled. This method can be useful as a
* storage reclamation operation, that has no other impact on
* functionality. Cancelled tasks are never executed, but may
* accumulate in work queues until worker threads can actively
* remove them. Invoking this method instead tries to remove them now.
* However, this method may fail to remove tasks in
* the presence of interference by other threads.*
*/
public void purge() {

但是有人可以告诉我工作线程在哪里主动删除源中已取消的任务吗?

感谢您的宝贵时间,

最佳答案

工作线程在正常操作期间会主动删除已取消的任务,当它们在 ThreadPoolExecutor.getTask() 中从工作队列中 take() 任务并尝试 run() 它们时。当代表 Runnable 工作单元的底层 FutureTask 调用其 FutureTask$Sync.innerRun() 时,它首先检查预期的 READY 状态 - 否则返回。因此,如果任务被取消,并且它已经从工作队列中删除,则执行将被跳过。如果任务已经在运行,FutureTask.cancel() 的 mayInterruptIfRunning 标志将确定是否尝试中断()。

这意味着,默认情况下,已取消的任务会一直保留在工作队列中,直到有可用的 Worker 尝试处理它、发现任务已取消并完成其处理。因此,关于队列大小的问题的答案取决于工作人员是否已完成其中任何任务。 ThreadPoolExecutor.purge()允许您手动触发立即遍历workQueue以删除已取消的任务。

关于java - 清理 ThreadPoolExecutor 中的有界队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18068207/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com