PriorityBlockingQueue is unbounded, but I need to bound it somehow. What is the best way to achieve that?
For information, the bounded PriorityBlo
If the order of the Runnables you want to execute is not strict (as is: it may occur that some lower priority tasks are executed even though higher priority tasks exist), then I would suggest the following, which boils down to periodically cutting the PriorityQueue down in size:
if (queue.size() > MIN_RETAIN * 2){
ArrayList toRetain = new ArrayList(MIN_RETAIN);
queue.drainTo(toRetain, MIN_RETAIN);
queue.clear();
for (T t : toRetain){
queue.offer(t);
}
}
This will obviously fail if the order needs to be strict, as draining will lead to a moment, wenn low priority task will retrieved from the queue using concurrent access.
The advantages are, that this is thread-safe and likely to get as fast as you can do with the priority queue design.