A Queue that additionally supports operations that wait for the queue to become non-empty when retrieving an element, and wait for space to become available in the queue when storing an element.
This is the javadoc for BlockingQueue
. You use it if you need this blocking behavior, otherwise you don't.
BlockingQueue
does not maintain any priority, it is strictly first-in-first-out. Perhaps you are using PriorityBlockingQueue
?
Coming to your pseudocode:
void addToQueue(SomeObject obj) {
... put it on my priority queue
... do some logging
}
The queue is thread-safe, but that only means that multiple threads can concurrently call put it on my priority queue
without any data corruption. It does not guarantee any of the following:
- If there are multiple threads blocked which one will succeed first
- If a
thread X
completes theput
before athread Y
thenthread X
will also complete thelogging
beforethread Y
.
If you need all of addToQueue
occur without interleaving from other threads then you need to synchronize. Note that you can use the queue object itself:
void addToQueue(SomeObject obj) {
synchronized (queue) {
... put it on my priority queue
... do some logging
}
}