Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Synchronizing method or entire queue?

If a queue is to be accessed by several threads, but it's currently only being modified by a single method getNextInQueue(), what's the most appropriate form of synchronizing access to the queue?

Currently, I declared the queue as a ConcurrentLinkedQueue, but I don't want to reach a deadlock where multiple threads are waiting for a lock to be released. Another way I can handle this is by not synchronizing the queue, but synchronizing getNextInQueue(). However, as this code is used in the future, I don't think this will scale as well. (Every programmer that makes modifications to the queue will have to ensure that she synchronizes the operation.)

Thoughts?

like image 863
Sal Avatar asked Dec 26 '22 21:12

Sal


2 Answers

I think the easiest, and most correct way is use the ConcurrentLinkedQueue. I do not believe this would cause a deadlock, however. The one thing I am not sure of, however, is how the Concurrent wrappers handle situations where you use an iterator. I seem to remember having to fall back to the old synchronized method of wrapping all calls to the underlying collection (reads and writes). I am pretty sure thats what the Concurrent wrapper is doing, though.

like image 140
CodeChimp Avatar answered Jan 06 '23 09:01

CodeChimp


If it's a ConcurrentLinkedQueue, and the queue state is only data shared between threads, you don't need to synchronize anything. That's the whole point of using a concurrent collection. A producer-consumer setup shouldn't deadlock unless you're doing something strange. (Like having the same thread be a producer and consumer.)

like image 28
millimoose Avatar answered Jan 06 '23 08:01

millimoose