    01: /**
    02:     A first-in, first-out bounded collection of messages.
    03: */
    04: public class MessageQueue
    05: {
    06:    /**
    07:        Constructs an empty message queue.
    08:        @param capacity the maximum capacity of the queue
    09:        @precondition capacity > 0
    10:    */
    11:    public MessageQueue(int capacity)
    12:    {
    13:       elements = new Message[capacity];
    14:       count = 0;
    15:       head = 0;
    16:       tail = 0;
    17:    }
    18:
    19:    /**
    20:        Remove message at head.
    21:        @return the message that has been removed from the queue
    22:        @precondition size() > 0
    23:    */
    24:    public Message removeFirst()
    25:    {
    26:       Message r = elements[head];
    27:       head = (head + 1) % elements.length;
    28:       count--;
    29:       return r;
    30:    }
    31:
    32:    /**
    33:        Append a message at tail.
    34:        @param aMessage the message to be appended
    35:        @precondition !isFull();
    36:    */
    37:    public void add(Message aMessage)
    38:    {
    39:       elements[tail] = aMessage;
    40:       tail = (tail + 1) % elements.length;
    41:       count++;
    42:    }
    43:
    44:    /**
    45:        Get the total number of messages in the queue.
    46:        @return the total number of messages in the queue
    47:    */
    48:    public int size()
    49:    {
    50:       return count;
    51:    }
    52:
    53:    /**
    54:        Checks whether this queue is full
    55:        @return true if the queue is full
    56:    */
    57:    public boolean isFull()
    58:    {
    59:       return count == elements.length;
    60:    }
    61:
    62:    /**
    63:        Get message at head.
    64:        @return the message that is at the head of the queue
    65:        @precondition size() > 0
    66:    */
    67:    public Message getFirst()
    68:    {
    69:       return elements[head];
    70:    }
    71:
    72:    private Message[] elements;
    73:    private int head;
    74:    private int tail;
    75:    private int count;
    76: }