/** * BoundedBuffer with blocking put and get * This class is thread-safe * Written by Brian Goetz and Tim Peierls * Revised by Andrew Whitaker for CSE451 */ public class BoundedBuffer { private final Object [] buf; private int tail; private int head; private int count; public BoundedBuffer(int capacity) { this.buf = new Object[capacity]; } public synchronized final void put(Object v) throws InterruptedException { while (isFull()) wait(); buf[tail] = v; if (++tail == buf.length) tail = 0; ++count; notifyAll(); } public synchronized final Object take() throws InterruptedException { while (isEmpty()) wait(); Object v = buf[head]; buf[head] = null; if (++head == buf.length) head = 0; --count; notifyAll(); return v; } public synchronized final boolean isFull() { return count == buf.length; } public synchronized final boolean isEmpty() { return count == 0; } }