Can I use PriorityBlockingQueue with multiple threads?

How many locks does PriorityBlockingQueue ? Are take and put operations synchronized? I could not find much information about this type of queue. I used single-threaded PriorityQueue .

+4
source share
3 answers

How many locks does BlockingQueue take precedence?

This is an implementation detail that does not matter. If you do not want to understand how this is implemented, in this case I can only offer you to look at the source code.

take and put operations in sync?

They are probably not synchronized strictly speaking, but the class is thread safe, so you can accept and put in multiple threads at the same time.

Note: javadoc PriorityBlockingQueue not very explicit in this question, but if you look in the javadoc of the java.util.concurrent package , you will see:

Five implementations in java.util.concurrent support the extended BlockingQueue interface, which defines the blocking versions of put and take: LinkedBlockingQueue, ArrayBlockingQueue, SynchronousQueue, PriorityBlockingQueue, and DelayQueue.

And BlockingQueue clearly states :

BlockingQueue implementations are thread safe . All queue methods implement their effects atomically using internal locks or other forms of concurrency control. However, addAll, containsAll, retainAll, and removeAll bulk collection operations are not necessarily atomic unless otherwise specified in the implementation.

+12
source

From reading the source code of HotSpot Java 7, there is only one lock called lock .

Various implementations are possible, as this is not a documented class requirement.

+1
source

From the Javadoc for PriorityBlockingQueue :

An unlimited blocking queue that uses the same ordering rules as the PriorityQueue class and blocks search operations. Although this queue is logically unlimited, add attempts may fail due to depletion of resources (raising OutOfMemoryError). This class does not allow null elements. The priority queue based on natural ordering also prevents the insertion of disparate objects (doing this leads to a ClassCastException).

Internal implementation does not matter.

0
source

Source: https://habr.com/ru/post/1446231/


All Articles