Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using LinkedBlockingQueue good enough for multi thread java program?

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.

like image 887
Dan Avatar asked Sep 26 '12 06:09

Dan


2 Answers

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.

like image 106
Tudor Avatar answered Oct 18 '22 14:10

Tudor


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?

like image 29
Amrish Pandey Avatar answered Oct 18 '22 15:10

Amrish Pandey