I have a consumer and a producer that adds and deletes Item objects from the queue. If I use the put()
and take()
methods. Is there any thread safety issues I need to still cover? This is similar to the bounded buffer problem and I was just wondering if using the blocking queue instead replaces the need for semaphores or monitors. The Item object itself would probably need synchronization (setters but getters don't need lock), am I right? And lastly, I'm not quite sure how to test if it is thread safe since I can't simultaneously make both threads call the take()
because to order of execution is underterministic. Any ideas? Thanks.
Asked
Active
Viewed 6,570 times
8

Dan
- 8,263
- 16
- 51
- 53
-
While the order of execution is nondeterministic, wouldn't the evidence that LBQ is not good enough be if some items you ``put()`` don't appear, or the same item item shows up repeatedly in the results from ``take()``? – michel-slm Sep 26 '12 at 06:43
-
I guess that is a possible test but it might not always be a thread specific test. Maybe using thread sleep in the middle of calling take() while other thread calls it too? – Dan Sep 26 '12 at 06:49
-
Its what Executors uses by default which leads me to the question; can you not use an ExecutorService which wraps a Queue and a Thread Pool? – Peter Lawrey Sep 26 '12 at 07:09
2 Answers
7
It is perfectly thread-safe for what you're doing, in fact this is what it's designed for. The description of BlockingQueue
(which is the interface implemented by LinkedBlockingQueue
) states:
BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control.

Tudor
- 61,523
- 12
- 102
- 142
1
Simultaneous put() and take() are not thread-safe since they use 2 different locks.
This is already answered here : Are LinkedBlockingQueue's insert and remove methods thread safe?

Community
- 1
- 1

Amrish Pandey
- 800
- 1
- 7
- 11
-
1I followed the link and found an answer to another post explaining why it is thread-safe. http://stackoverflow.com/questions/26543807/is-blockingqueue-completely-thread-safe-in-java/26543940#26543940 – user1266174 Jul 29 '15 at 23:17