Synchronization method or whole queue?

If multiple threads are accessing a queue, but it is currently being changed by only one getNextInQueue() method, what is the most suitable form of queue access synchronization?

Currently, I have declared the queue as ConcurrentLinkedQueue , but I do not want to go to a dead end where several threads are waiting for the lock to exit. Another way I can handle this is not by queue synchronization, but by getNextInQueue() synchronization. However, since this code will be used in the future, I don’t think it will scale. (Every programmer who makes changes to the queue will need to make sure that it synchronizes the operation.)

Thoughts?

+4
source share
3 answers

I think the easiest and most correct way is to use ConcurrentLinkedQueue . However, I do not believe that this could lead to a deadlock. However, I'm not sure how parallel shells handle situations when you use an iterator. It seems that I remember that I had to go back to the old synchronized method to transfer all the calls to the base collection (read and write). I am sure this is what the Concurrent container does.

+5
source

If this is a ConcurrentLinkedQueue and the queue state is just the data shared between the threads, you do not need to synchronize anything. It's all about using a parallel collection. Producer-consumer tuning should not be at a standstill unless you do something strange. (Just as the same thread is a producer and a consumer.)

+3
source

synchronizing only getNext() would not be a good idea - if you want to do this, you will also have to synchronize insert .

Example:
If there are no elements in the queue and thread A tries to execute getNext() and has not completed the method, you can insert a new element into the queue on thread B, which will cause thread A to wait on the queue, even if it has a new element.

To summarize :
If importance is important, I stay with ConcurrentLinkedQueue

+2
source

All Articles