Java LinkedBlockingQueue 的插入和删除方法线程安全吗?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2695426/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Are LinkedBlockingQueue's insert and remove methods thread safe?
提问by Steve Kuo
I'm using LinkedBlockingQueue
between two different threads. One thread adds data via add
, while the other thread receives data via take
.
我LinkedBlockingQueue
在两个不同的线程之间使用。一个线程通过 来添加数据add
,而另一个线程通过 接收数据take
。
My question is, do I need to synchronize access to add
and take
. Is LinkedBlockingQueue
's insert and remove methods thread safe?
我的问题是,我是否需要同步访问add
和take
. 是LinkedBlockingQueue
的插入和删除方法是线程安全的?
采纳答案by Matthew Flaschen
Yes. From the docs:
是的。从文档:
"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 不一定以原子方式执行。因此,例如,在仅添加 c 中的某些元素后,addAll(c) 可能会失败(抛出异常)。”
回答by Amrish Pandey
Yes, BlockingQueue
methods add()
and take()
are thread safe but with a difference.
是的,BlockingQueue
方法add()
和take()
是线程安全的,但有区别。
add ()
and take()
method uses 2 different ReentrantLock
objects.
add ()
和take()
方法使用 2 个不同的ReentrantLock
对象。
add(
) method uses
add(
) 方法使用
private final ReentrantLock putLock = new ReentrantLock();
take()
method uses
take()
方法使用
private final ReentrantLock takeLock = new ReentrantLock();
Hence, simultaneous access to add()
method is synchronized. Similarly, simultaneous access to take()
method is synchronized
.
因此,同时访问add()
方法是同步的。同样,同时访问take()
方法是synchronized
。
But, simultaneous access to add()
and take()
method is not synchronized
since they are using 2 different lock objects (except during edge condition of queue full / empty).
但是,不能同时访问add()
和take()
方法,synchronized
因为它们使用了 2 个不同的锁定对象(队列已满/空的边缘条件除外)。
回答by Java Guru
Simply Yes, its definitely thread safe otherwise it wouldn't have qualified as a candidate for storing element for ThreadPoolExecutor.
是的,它绝对是线程安全的,否则它就没有资格作为ThreadPoolExecutor存储元素的候选者。
Simply add and retrieve element without worrying about concurrency for BlockingQueue.
只需添加和检索元素,无需担心 BlockingQueue 的并发性。