Code/Buffer.java

From PKC
Revision as of 14:24, 25 August 2021 by KevinTung (talk | contribs) (Created page with "<syntaxhighlight lang="java"> public class Buffer<E> { public final int capacity; private final E[] store; private int head, tail, size; @SuppressWarnings("unchecked...")
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search
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;
  }
}