Why won't PriorityQueue act as a queue?

I am using PriorityBlockingQueue with a priority field. In my test, I use System#currentTime() for priorities - the same priorities are obtained on the computer so fast that the milliseconds are the same (or more like milliseconds on a PC with a valid margin of error).

When the priorities are the same, the queue works as if its stack, which seems strange. Is there an alternative to the fact that the queue works as if it were a normal queue (i.e., FIFO, not LIFO behavior) when the priorities of the elements are the same?

+6
source share
4 answers

Operations on this class give no guarantees regarding the ordering of elements with equal priority. If you need to enforce order, you can define custom classes or comparators that use a secondary key to break ties in primary priority values.

PriorityBlockingQueue docs will tell you this, and how to get around it if you need to.

+11
source

I do not think that the priority queue guarantees the procedure for obtaining equal elements. One option is to make the priority more complex - click on the negative size of the queue when you click on an element with its priority and compare these values ​​for elements with equal priority.

+2
source

Just create a PriorityBlockingQueue with your own comparator that takes into account creation time (see http://docs.oracle.com/javase/6/docs/api/java/util/concurrent/PriorityBlockingQueue.html # PriorityBlockingQueue (int, java.util .Comparator) ). You may need to change your keys from a simple Date to a Date and counter class, where the latter will receive a global increase with each creation (static field of your new key class); it’s not FIFO, but First First First Out.

Or just implement your own PriorityQueueFifo class.

+1
source

Another solution is to keep the counter in your tests, which you use for priority, and which you increment with each insert. That way, your priority queue will have a FIFO order in your tests, but it will look like an arbitrary priority queue.

0
source

Source: https://habr.com/ru/post/914724/


All Articles