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?
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.
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.)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With