Related questions:
Try this code:
public class BoundedPQueue> {
/**
* Lock used for all public operations
*/
private final ReentrantLock lock;
PriorityBlockingQueue queue ;
int size = 0;
public BoundedPQueue(int capacity){
queue = new PriorityBlockingQueue(capacity, new CustomComparator());
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> implements Comparator {
@Override
public int compare(E o1, E o2) {
//give me a max heap
return o1.compareTo(o2) *-1;
}
}
}