gpt4 book ai didi

java - 是否同步到足以使 BlockingQueue 的 drainTo() 方法原子化?

转载 作者:搜寻专家 更新时间:2023-11-01 02:06:44 25 4
gpt4 key购买 nike

如果我只是做这样的事情:

synchronized(taskQueue) { //taskQueue is a BlockingQueue 
taskQueue.drainTo(tasks); //tasks is a list
}

我确定不能在同步块(synchronized block)内执行对 taskQueue.put()taskQueue.take() 的并发调用吗?

换句话说,我是否使 drainTo() 方法成为原子方法?

或者更一般地说,我如何使线程安全操作的组合成为原子?

例子:

if(taskQueue.size() == 1) {
/*Do a lot of things here, but I do not want other threads
to change the size of the queue here with take or put*/
}
//taskQueue.size() must still be equal to 1

最佳答案

请参阅以下摘录自 Java docs of BlockingQueue

BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation. So it is possible, for example, for addAll(c) to fail (throwing an exception) after adding only some of the elements in c.

此外,请查看示例,该示例显示 BlockingQueue 实现可以安全地用于多个生产者和多个消费者。

因此,如果您没有使用 addAll、containsAll、retainAll 和 removeAll 等批量收集操作,那么您就是线程安全的。

您甚至不需要synchronized(taskQueue) {,可以直接使用taskQueue.drainTo(tasks);,因为BlockingQueue 实现是线程安全的 用于非批量收集操作,如 puttakedrainTo

希望这对您有所帮助!

关于java - 是否同步到足以使 BlockingQueue 的 drainTo() 方法原子化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30964375/

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