Bounded PriorityBlockingQueue

后端 未结 9 1090
Happy的楠姐
Happy的楠姐 2021-01-01 17:47

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

For information, the bounded PriorityBlo

9条回答
  •  借酒劲吻你
    2021-01-01 17:55

    Of the top of my head, I'd subclass it and overwrite the put method to enforce this. If it goes over throw an exception or do whatever seems appropriate.

    Something like:

    public class LimitedPBQ extends PriorityBlockingQueue {
    
        private int maxItems;
        public LimitedPBQ(int maxItems){
            this.maxItems = maxItems;
        }
    
        @Override
        public boolean offer(Object e) {
            boolean success = super.offer(e);
            if(!success){
                return false;
            } else if (this.size()>maxItems){
                // Need to drop last item in queue
                // The array is not guaranteed to be in order, 
                // so you should sort it to be sure, even though Sun's Java 6 
                // version will return it in order
                this.remove(this.toArray()[this.size()-1]);
            }
            return true;
        }
    }
    

    Edit: Both add and put invoke offer, so overriding it should be enough

    Edit 2: Should now remove the last element if over maxItems. There may be a more elegant way of doing it though.

提交回复
热议问题