Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why would a PriorityQueue not act like a Queue?

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?

like image 269
Ben Avatar asked May 02 '12 14:05

Ben


People also ask

Is a PriorityQueue always sorted?

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.

Is a Priority Queue a queue?

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.

Does PriorityQueue maintain insertion order?

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.

What is the purpose of the PriorityQueue comparator in the code?

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.


2 Answers

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.

like image 62
Louis Wasserman Avatar answered Sep 21 '22 01:09

Louis Wasserman


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.

like image 40
Ivaylo Strandjev Avatar answered Sep 22 '22 01:09

Ivaylo Strandjev