Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Are LinkedBlockingQueue's insert and remove methods thread safe?

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?

like image 642
Steve Kuo Avatar asked Apr 23 '10 00:04

Steve Kuo


People also ask

Is Threadsafe an ArrayBlockingQueue?

ArrayBlockingQueue is thread-safe. The Iterator provided in iterator() method traverses the elements in order from first (head) to last (tail). It supports an optional fairness policy for ordering waiting producer and consumer threads.

What is a thread-safe method?

Thread safety is a computer programming concept applicable to multi-threaded code. Thread-safe code only manipulates shared data structures in a manner that ensures that all threads behave properly and fulfill their design specifications without unintended interaction.

What is LinkedBlockingQueue?

The LinkedBlockingQueue is an optionally-bounded blocking queue based on linked nodes. It means that the LinkedBlockingQueue can be bounded, if its capacity is given, else the LinkedBlockingQueue will be unbounded. The capacity can be given as a parameter to the constructor of LinkedBlockingQueue.


1 Answers

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

like image 59
Matthew Flaschen Avatar answered Sep 20 '22 16:09

Matthew Flaschen