I am using the PriorityBlockingQueue
with a priority field. In my test I use System#currentTime()
for priorities—the same priorities are obtained by the computer being so quick that the milliseconds are the same (or more like the milliseconds on a PC has a margin of error).
When the priorities are the same the queue acts as if it’s a stack, which seems strange. Is there an alternative to make the queue act as if it’s a normal queue (that is, FIFO rather than LIFO behavior) when the priorities of the elements are the same?
A PriorityQueue is what is called a binary heap. It is only ordered/sorted in the sense that the first element is the least. In other word, it only cares about what is in the front of the queue, the rest are "ordered" when needed.
A priority queue is a special type of queue in which each element is associated with a priority value. And, elements are served on the basis of their priority. That is, higher priority elements are served first. However, if elements with the same priority occur, they are served according to their order in the queue.
PriorityQueue doesn't need to be ordered, instead, it focuses on head of data. Insertion is in O(log n) time. Sorting wastes time and useless for a queue. Moreover, either the element is-a Comparable , or a Comparator is provided.
Creates a PriorityQueue with the specified initial capacity that orders its elements according to the specified comparator. comparator - the comparator that will be used to order this priority queue. If null , the natural ordering of the elements will be used.
Operations on this class make no guarantees about the ordering of elements with equal priority. If you need to enforce an ordering, you can define custom classes or comparators that use a secondary key to break ties in primary priority values.
The PriorityBlockingQueue
docs themselves tell you this, and how to get around it if you need to.
I do not think the priority queue guarantees the order of getting equal elements. One option is to have the priority more complex - push the negative of the size of the queue when pushing the element along with its priority and compare these values for equal priority elements.
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