Using blocking thread-safe queue ordered by priority

When you work with data structures, you may typically feel the need to have an ordered queue. Java provides PriorityBlockingQueue that has this functionality.

All the elements you want to add to PriorityBlockingQueue have to implement the Comparable interface; alternatively, you can include Comparator in the queue's constructor. This interface has a method called compareTo() that receives an object of the same type. So you have two objects to compare: the one that is executing the method and the one that is received as a parameter. The method must return a number less than zero if the local object is less than the parameter. It should return a number bigger than zero if the local object is greater than the parameter. The number must be zero if both the objects are equal.

PriorityBlockingQueue uses the compareTo() method when you insert an element in it to determine the position of the element inserted. Bigger elements will either be the tail or head of the queue, depending on the compareTo() method.

Another important characteristic of PriorityBlockingQueue is that it's a blocking data structure. It has methods that, if unable to perform the operation immediately, will block the thread until they are able to do it.

In this recipe, you will learn how to use the PriorityBlockingQueue class by implementing an example, where you are going to store a lot of events with different priorities in the same list, to check that the queue will be ordered as you want.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.119.130.20