java - 如何以线程安全的方式访问ThreadpoolExecutor的底层队列

标签 java executors

getQueue()方法提供了对ThreadPoolExecutor中底层阻塞队列的访问,但这似乎并不安全。

遍历此函数返回的队列可能会错过 ThreadPoolExecutor 对队列进行的更新。

“方法 getQueue() 允许访问工作队列以进行监视和调试。强烈建议不要将此方法用于任何其他目的。”

如果你想遍历ThreadPoolExecutor使用的workQueue你会怎么做?或者有其他方法吗?

这是……的延续。 Choosing a data structure for a variant of producer consumer problem

现在,我正在尝试多个生产者多个消费者,但我想使用一些现有的线程池,因为我不想自己管理线程池,而且我还想在 ThreadPoolExecutor 完成执行某些任务时进行回调能够以线程安全的方式检查“正在进行的事务”数据结构。

最佳答案

您可以重写 beforeExecute 和 afterExecute 方法,让您知道任务已开始和完成。您可以重写exe​​cute()来了解任务何时添加。

您遇到的问题是队列并非设计用于查询,并且任务可能会在您看到它之前就被消耗掉。解决这个问题的一种方法是创建您自己的队列实现(可能覆盖/包装 ConcurrentLinkedQueue)

顺便说一句:队列是线程安全的,但不能保证您会看到每个条目。

ConcurrentLinkedQueue.iterator() 被记录为

Returns an iterator over the elements in this queue in proper sequence. The returned iterator is a "weakly consistent" iterator that will never throw ConcurrentModificationException, and guarantees to traverse elements as they existed upon construction of the iterator, and may (but is not guaranteed to) reflect any modifications subsequent to construction.

关于java - 如何以线程安全的方式访问ThreadpoolExecutor的底层队列,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5935454/

相关文章:

java - 在 hibernate 和 glassfish 3.0.1 中使用 log4j

java - 插入到 Impala 表与写入 HDFS

java - 如何访问自定义线程池执行器方法中的线程对象?

python - Spark - 为我的 Spark 作业分配了多少执行器和内核

python - 在chronos中为docker自定义mesos执行程序

Java逐元素读取字符串中的元素

java - Spring MVC : URL Pattern

amazon-web-services - AWS lambda 中的执行器服务

memory - 如何避免 Spark executor 丢失以及由于内存限制而导致 yarn 容器杀死它?

Java动态绑定(bind)调用父类方法