How it works...

In this example, you implemented a priority queue of Event objects using PriorityBlockingQueue. As mentioned in the introduction, all the elements stored in PriorityBlockingQueue have to implement the Comparable interface or provide a Comparator object to the constructor of the queue. In this case, you used the first approach, so you implemented the compareTo() method in the Event class.

All the events have a priority attribute. The elements that have a higher value of priority will be the first elements in the queue. When you implement the compareTo() method, if the event executing the method has a priority higher than the priority of the event passed as a parameter, it returns -1 as the result. In another case, if the event ...

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.