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 ...

Get Java 9 Concurrency Cookbook - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.