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.
3 Answers
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.
Comments
From the Javadoc for PriorityBlockingQueue:
An unbounded blocking queue that uses the same ordering rules as class PriorityQueue and supplies blocking retrieval operations. While this queue is logically unbounded, attempted additions may fail due to resource exhaustion (causing OutOfMemoryError). This class does not permit null elements. A priority queue relying on natural ordering also does not permit insertion of non-comparable objects (doing so results in ClassCastException).
The internal implementation is irrelevant.
BlockingQueuejavadocs it says "BlockingQueue implementations are thread-safe".takeandputare synchronised. Which means that if we think of it as having a single lock, it's a good mental model. There won't be any unexpected surprises.