0% found this document useful (0 votes)
95 views2 pages

Bounded Blocking Queue Implementation

This class implements a bounded blocking queue with a fixed capacity. It uses a ReentrantLock and two Condition variables, one for signaling when the queue is full and one for empty, to synchronize producer and consumer threads such that enqueue blocks when full and dequeue blocks when empty. Enqueue adds an element and signals empty, while dequeue removes an element and signals full.

Uploaded by

Rui Zhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
95 views2 pages

Bounded Blocking Queue Implementation

This class implements a bounded blocking queue with a fixed capacity. It uses a ReentrantLock and two Condition variables, one for signaling when the queue is full and one for empty, to synchronize producer and consumer threads such that enqueue blocks when full and dequeue blocks when empty. Enqueue adds an element and signals empty, while dequeue removes an element and signals full.

Uploaded by

Rui Zhan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as RTF, PDF, TXT or read online on Scribd
You are on page 1/ 2

class BoundedBlockingQueue {

        int capacity = 0;
        ReentrantLock lk = new ReentrantLock();
        Condition full = lk.newCondition();
        Condition empty = lk.newCondition();
        private Queue<Integer> queue = new LinkedList<>();

        public BoundedBlockingQueue(int capacity) {


                this.capacity = capacity;
    }
    
        public void enqueue(int element) throws InterruptedException {
                lk.lock();
                try{
                        while(queue.size() == capacity) {
                                full.await();
            }

                        queue.add(element);
                        empty.signal();
                } finally {
                        lk.unlock();
        }
    }
    
        public int dequeue() throws InterruptedException {
                lk.lock();
                int res = -1;
                try {
                        while(queue.size() == 0) {
                                empty.await();
            }

                        res = queue.poll();
                        full.signal();
                } finally {
                        lk.unlock();
        }
                return res;
    }
    
        public int size() {
                return queue.size();
    }
}

You might also like