Suppose I create a thread safe object:
PriorityBlockingQueue<Object> safeQueue = new PriorityBlockingQueue<Object>();
If I synchronize on it:
synchronized (safeQueue) {
....
}
Does code that block:
// some non-synchronized block
Object value = safeQueue.poll();
No. The only time you get any blocking is if another thread is also doing a
synchronizedon the same object. If your code issynchronized (safeQueue)then a call toPriorityBlockingQueue.poll()would only block ifpoll()was asynchronizedmethod or if the code usedsynchronized (this)code.When you call
safeQueue.poll()thePriorityBlockingQueuecode is actually using an internalReentrantLock, and not doing asynchronized (this). Here’s the code forpoll():Lastly, as you mention,
PriorityBlockingQueueis already reentrant so you do not need to synchronize on it to allow multiple threads to access the queue. You could still need to synchronize on it if you needed to solve race conditions in your own code of course.