001package horstmann.ch09_queue3;
002import java.util.ArrayList;
003/**
004    A first-in, first-out bounded collection of objects.
005 */
006public class BoundedQueue<E>
007{
008        /**
009       Constructs an empty queue.
010       @param capacity the maximum capacity of the queue
011         */
012        public BoundedQueue(int capacity)
013        {
014                elements = new ArrayList<E>(capacity);
015                head = 0;
016                tail = 0;
017                size = 0;
018        }
019
020        /**
021       Removes the object at the head.
022       @return the object that has been removed from the queue
023         */
024        public synchronized E remove()
025                        throws InterruptedException
026        {
027                while (size == 0) wait();
028                E r = elements.get(head);
029                head++;
030                size--;
031                if (head == elements.size())
032                        head = 0;
033                notifyAll();
034                return r;
035        }
036
037        /**
038       Appends an object at the tail.
039       @param newValue the object to be appended
040         */
041        public synchronized void add(E newValue)
042                        throws InterruptedException
043        {
044                while (size == elements.size()) wait();
045                elements.set(tail,newValue);
046                tail++;
047                size++;
048                if (tail == elements.size())
049                        tail = 0;
050                notifyAll();
051        }
052
053        private ArrayList<E> elements;
054        private int head;
055        private int tail;
056        private int size;
057}