Buffer.java

(download)

public class Buffer<E> {

  public final int capacity;
  private final E[] store;
  private int head, tail, size;

  @SuppressWarnings("unchecked")
  public Buffer (int capacity) {
    this.capacity = capacity;
    this.store = (E[])new Object[capacity];
  }
  private int next (int x) {
    return (x + 1) % store.length;
  }
  public synchronized void put (E e) throws InterruptedException {
    while (isFull())
      wait();
    notify();
    store[tail] = e;
    tail = next(tail);
    size++;
  }
  public synchronized E get () throws InterruptedException {
    while (isEmpty())
      wait();
    notify();
    E e = store[head];
    store[head] = null; // for GC
    head = next(head);
    size--;
    return e;
  }
  public synchronized boolean isFull () {
    return size == capacity;
  }
  public synchronized boolean isEmpty () {
    return size == 0;
  }
}