Related questions:
Exactly what I was looking for. However, the implementation contains a bug:
Namely: if elementsLeft > 0 and e is already contained in the TreeSet. In this case, elementsLeft is decreased, but the number of elements in the TreeSet stays the same.
I would suggest to replace the corresponding lines in the add() method by
} else if (elementsLeft > 0) {
// queue isn't full => add element and decrement elementsLeft
boolean added = super.add(e);
if (added) {
elementsLeft--;
}
return added;
Try this code:
public class BoundedPQueue<E extends Comparable<E>> {
/**
* Lock used for all public operations
*/
private final ReentrantLock lock;
PriorityBlockingQueue<E> queue ;
int size = 0;
public BoundedPQueue(int capacity){
queue = new PriorityBlockingQueue<E>(capacity, new CustomComparator<E>());
size = capacity;
this.lock = new ReentrantLock();
}
public boolean offer(E e) {
final ReentrantLock lock = this.lock;
lock.lock();
E vl = null;
if(queue.size()>= size) {
vl= queue.poll();
if(vl.compareTo(e)<0)
e=vl;
}
try {
return queue.offer(e);
} finally {
lock.unlock();
}
}
public E poll() {
return queue.poll();
}
public static class CustomComparator<E extends Comparable<E>> implements Comparator<E> {
@Override
public int compare(E o1, E o2) {
//give me a max heap
return o1.compareTo(o2) *-1;
}
}
}
Though an old question but it may be helpful to somebody else. You can use minMaxPriorityQueue of Google's Java library guava.