Source of BoundedQueue.java


  1: /** 
  2:     A first-in, first-out bounded collection of objects. 
  3: */ 
  4: public class BoundedQueue<E>
  5: { 
  6:    /** 
  7:        Constructs an empty queue. 
  8:        @param capacity the maximum capacity of the queue 
  9:    */ 
 10:    public BoundedQueue(int capacity) 
 11:    { 
 12:       elements = new Object[capacity]; 
 13:       head = 0; 
 14:       tail = 0; 
 15:       size = 0;
 16:    } 

 18:    /** 
 19:        Removes the object at the head. 
 20:        @return the object that has been removed from the queue
 21:    */ 
 22:    public synchronized E remove() 
 23:          throws InterruptedException
 24:    { 
 25:       while (size == 0) wait();
 26:       E r = (E) elements[head]; 
 27:       head++;
 28:       size--;
 29:       if (head == elements.length) 
 30:          head = 0; 
 31:       notifyAll();
 32:       return r; 
 33:    } 

 35:    /** 
 36:        Appends an object at the tail. 
 37:        @param newValue the object to be appended 
 38:    */ 
 39:    public synchronized void add(E newValue) 
 40:          throws InterruptedException
 41:    { 
 42:       while (size == elements.length) wait();
 43:       elements[tail] = newValue; 
 44:       tail++;
 45:       size++;
 46:       if (tail == elements.length) 
 47:          tail = 0; 
 48:       notifyAll();
 49:    } 

 51:    private Object[] elements; 
 52:    private int head; 
 53:    private int tail; 
 54:    private int size;
 55: }