Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bounded PriorityBlockingQueue

PriorityBlockingQueue is unbounded, but I need to bound it somehow. What is the best way to achieve that?

For information, the bounded PriorityBlockingQueue will be used in a ThreadPoolExecutor.

NB: By bounded I don't want to throw Exception if that happens, I want to put the object in the queue and then cut it based on its priority value. Is there any good way to do this cut thingie?

like image 373
nanda Avatar asked Feb 26 '10 12:02

nanda


Video Answer


2 Answers

I actually wouldn't subclass it. While I can't put together example code right now, I'd suggest a version of the decorator pattern.

Create a new class and implement the interfaces implemented by your class of interest: PriorityBlockingQueue. I've found the following interfaces used by this class:

Serializable, Iterable<E>, Collection<E>, BlockingQueue<E>, Queue<E>

In the constructor for a class, accept a PriorityBlockingQueue as a constructor parameter.

Then implement all the methods required by the interfaces via the instances of the PriorityblockingQueue. Add any code required to make it Bounded. This is a fairly standard implementation of a Decorator pattern.

like image 61
Frank V Avatar answered Oct 11 '22 10:10

Frank V


There's an implementation of this in the Google Collections/Guava library: MinMaxPriorityQueue.

A min-max priority queue can be configured with a maximum size. If so, each time the size of the queue exceeds that value, the queue automatically removes its greatest element according to its comparator (which might be the element that was just added). This is different from conventional bounded queues, which either block or reject new elements when full.

like image 24
rescdsk Avatar answered Oct 11 '22 10:10

rescdsk