Java BlockingQueue with batching?

前端 未结 5 1539
有刺的猬
有刺的猬 2021-01-01 16:00

I am interested in a data structure identical to the Java BlockingQueue, with the exception that it must be able to batch objects in the queue. In other words, I would like

5条回答
  •  说谎
    说谎 (楼主)
    2021-01-01 16:20

    Here is a quick ( = simple but not fully tested) implementation that i think may be suitable for your requests - you should be able to extend it to support the full queue interface if you need to.

    to increase performance you can switch to ReentrantLock instead of using "synchronized" keyword..

    public class BatchBlockingQueue {
    
        private ArrayList queue;
        private Semaphore readerLock;
        private Semaphore writerLock;
        private int batchSize;
    
        public BatchBlockingQueue(int batchSize) {
            this.queue = new ArrayList<>(batchSize);
            this.readerLock = new Semaphore(0);
            this.writerLock = new Semaphore(batchSize);
            this.batchSize = batchSize;
        }
    
        public synchronized void put(T e) throws InterruptedException {
            writerLock.acquire();
            queue.add(e);
            if (queue.size() == batchSize) {
                readerLock.release(batchSize);
            }
        }
    
        public synchronized T poll() throws InterruptedException {
            readerLock.acquire();
            T ret = queue.remove(0);
            if (queue.isEmpty()) {
                writerLock.release(batchSize);
            }
            return ret;
        }
    
    }
    

    Hope you find it useful.

提交回复
热议问题