Are LinkedBlockingQueue bound and remove methods thread safe?

I am using a LinkedBlockingQueue between two different threads. One thread adds data through add , and another thread receives data through take .

My question is: I need to synchronize access to add and take . LinkedBlockingQueue Insert and remove thread safe methods?

+42
java multithreading synchronization concurrency
Apr 23 2018-10-10T00:
source share
3 answers

Yes. From the docs :

"Blocking a Queue implementation is thread-safe. All queue methods achieve their effects using atoms internal locks or other forms of concurrency. However, the bulk of addAll, containsAll, remove all and removeAll collectible operations are not necessarily performed unless otherwise specified in the implementation. So, this is possible for example, addAll (c) fails (throwing an exception) after adding only some of the elements in s. "

+45
Apr 23 '10 at 0:27
source share
— -

Yes, BlockingQueue add() and take() methods are thread safe , but with a difference .

add () and take() methods use 2 different ReentrantLock .

add( ) uses

 private final ReentrantLock putLock = new ReentrantLock(); 

take() uses

 private final ReentrantLock takeLock = new ReentrantLock(); 

Therefore, simultaneous access to the add() method is synchronized. Similarly, concurrent access to the take() method is synchronized .

But simultaneous access to the add() and take() methods is not synchronized since they use 2 different locking objects (except that the condition for the end of the queue is equal to / empty).

+8
Feb 25 '14 at 6:19 06:19
source share

Just Yes, it is definitely thread safe, otherwise it would not be qualified as a candidate for storing an element for ThreadPoolExecutor .

Just add and remove an element without worrying about concurrency for BlockingQueue.

0
Dec 21 '15 at 18:14
source share



All Articles