Search code examples
javaconcurrencyjava.util.concurrent

How can I restrict the size of the LinkedTransferQueue?


I am implementing the producer/consumer pattern and using LinkedTransferQueue collection.

I do not want my producer to exceed certain memory limitations.

Currently I am using this check, but from the documentation, size operation require O(N) traversal. For my current implementation it is fine,

but is there any better approach than the one, which I am currently using ?

LinkedTransferQueue<String> producerStringLinkedTransferQueue = new LinkedTransferQueue<String>();

if (producerStringLinkedTransferQueue.size() <= 5000) {
    producerStringLinkedTransferQueue.add(<some data>);
}

Solution

  • If you want do nothing when queue is full (not replace its oldest item as, for example, Apache commons collections CircularFifoQueue does), then you can wrap LinkedTransferQueue in your custom class and implement needed methods for calculating queue's size:

    public class LimitLinkedTransferQueue<E> {
        LinkedTransferQueue<E> queue = new LinkedTransferQueue<>();
        private final long maxSize;
        private long size = 0;
    
        public LimitLinkedTransferQueue(long maxSize) {
            super();
            this.maxSize = maxSize;
        }
    
        public boolean add(E e) {
            if (this.size == this.maxSize){
                return false;
            }
            boolean result = queue.add(e);
            if (result) {
                size++;
            }
            return result;
        }
    
        public E take() throws InterruptedException {
            E item = queue.take();
            size--;
            return item;
        }
        // other need methods
    }