How many locks does PriorityBlockingQueue
have?
Are the take
and put
operations synchronized?
I couldnt find much information regarding this type of queue. I was using the single threaded PriorityQueue
.
PriorityBlockingQueue is a thread-safe and blocking variant of the PriorityQueue. In the linked article, you will also learn what a priority queue is. As with PriorityQueue , the elements are stored in an array representing a min-heap. The iterator iterates through the elements in the corresponding order.
It's also worth mentioning that the BlockingQueue interface also provides us with ways of blocking when adding to full queues. However, a PriorityBlockingQueue is unbounded. This means that it will never be full, thus it will always possible to add new elements.
Since PriorityQueue is not thread-safe, java provides PriorityBlockingQueue class that implements the BlockingQueue interface to use in a java multithreading environment.
So, it's considered to be thread-safe and can be safely called by multiple threads at the same time. All threads can safely call the factorial() method and will get the expected result without interfering with each other and without altering the output that the method generates for other threads.
How many locks PriorityBlockingQueue have?
That is an implementation detail that does not matter. Unless you want to understand how it is implemented in which case I can only suggest that you looked at the source code.
take and put operations are synchronized?
They are probably not synchronized strictly speaking, but the class is thread safe so you can take and put simultaneously in several threads.
Note: the javadoc of PriorityBlockingQueue
is not very explicit on that point, but if you look at the javadoc of the java.util.concurrent package, you will see:
Five implementations in java.util.concurrent support the extended BlockingQueue interface, that defines blocking versions of put and take: LinkedBlockingQueue, ArrayBlockingQueue, SynchronousQueue, PriorityBlockingQueue, and DelayQueue.
And BlockingQueue
clearly states:
BlockingQueue implementations are thread-safe. All queuing methods achieve their effects atomically using internal locks or other forms of concurrency control. However, the bulk Collection operations addAll, containsAll, retainAll and removeAll are not necessarily performed atomically unless specified otherwise in an implementation.
From reading the HotSpot Java 7 source code there is only one lock, called lock
.
Different implementations are possible as this is not a documented requirement of the class.
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