Are LinkedBlockingQueue's insert and remove methods thread safe?

Steve Kuo picture Steve Kuo · Apr 23, 2010 · Viewed 35k times · Source

I'm using LinkedBlockingQueue between two different threads. One thread adds data via add, while the other thread receives data via take.

My question is, do I need to synchronize access to add and take. Is LinkedBlockingQueue's insert and remove methods thread safe?

Answer

Matthew Flaschen picture Matthew Flaschen · Apr 23, 2010

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."