/** * BoundedBuffer base class without blocking * * 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]; } // TODO: block callers if the queue is full public synchronized final void put(Object v) { buf[tail] = v; if (++tail == buf.length) tail = 0; ++count; } // TODO: block callers if the queue is empty public synchronized final Object take() { Object v = buf[head]; buf[head] = null; if (++head == buf.length) head = 0; --count; return v; } public synchronized final boolean isFull() { return count == buf.length; } public synchronized final boolean isEmpty() { return count == 0; } }