CMPE 261 - Lab worksheet - Week 10

Problem 1: Unsafe buffer implementation

A buffer is a limited length FIFO(first-in-first-out) queue, common in many applications. It has a certain capacity, and one can push and pop values from it, as a queue. Thus an interace as follows can be used to represent a buffer:

    interface Buffer<T> {
        /**Returns true if the buffer has at least one empty slot*/
        boolean hasEmptySlot();

        /**Returns total capacity of the buffer*/    
        int totalCapacity();

        /**Pushes one element onto the end of buffer, throws exception if it has no empty space */
        void push(T) throws Exception;

        /**Pops one element from the top of the buffer */
        T pop() throws Exception;
    }

Write a generic typed class to implement a buffer of given type.

HINT: A circular buffer is the easiest implementation for this problem. In this implementation you can use an array storage as if its end is connected to its beginning. One pointer shows the slot to push the next value, and another shows the slot to pop the next value, both pointing to 0th element of the array at the beginning. If the two pointers are the same then there's nothing in the buffer. You must also maintain the number of elements in the buffer to understand that it is full.

Problem 1: Safe buffer implementation

Modify your class to obtain a buffer object which is safe against concurrent modifications by multiple threads.