/* * Class representing circular buffer with 5 elements. * Synchronized methods prevent simultaneous * reading and writing - monitor structure */ import javax.swing.*; class HoldInteger{ private static final int BUFFER_SIZE = 5; // size of buffer protected static final int EMPTY = 0; // code for empty slot protected int[] sharedInt = {EMPTY,EMPTY,EMPTY,EMPTY,EMPTY}; protected boolean writeable = true; // start out able to write into buffer protected boolean readable = false; // but nothing to read protected int readLoc = 0, writeLoc = 0; // where to next read or write in buffer protected JTextArea output; // Place to write buffer status // initialize buffer and save text area for writing public HoldInteger(JTextArea out) { output = out; } // Write value in buffer public synchronized void setSharedInt(int value) { while(!writeable){ // No room to write - wait until notified something there try{ // wait is in loop in case someone else sneaks in output.append("\nWaiting to produce "+value+"\n"); wait(); } catch (InterruptedException ie){ System.out.println("Exception: "+ie.toString()); } } sharedInt[writeLoc] = value; // insert value into buffer readable = true; // let others know will now be something to read output.append("\nProduced "+value+" into cell "+writeLoc); writeLoc = (writeLoc+1) % BUFFER_SIZE; // move index of next slot to write to output.append("\nready to write to "+writeLoc+" and read from "+readLoc); printBuffer(output,sharedInt); // print buffer contents if (writeLoc == readLoc) // buffer is full now { writeable = false; output.append("\nBuffer full\n"); } notifyAll(); // Notify everyone waiting that something has happened. } // return next available integer in buffer public synchronized int getSharedInt() { int value; // Data item to be returned while (!readable) // nothing to read - wait until notified something there { // Put in loop in case some other process sneaks in try{ output.append("\nWaiting to consume\n"); wait(); } catch (InterruptedException ie){ System.out.println("Exception: "+ie.toString()); } } writeable = true; // since reading, now room to write something value = sharedInt[readLoc]; // Get value from buffer sharedInt[readLoc] = EMPTY; // fill removed slot w/ -1 to make display clearer output.append("\nConsumed "+value+" from cell "+readLoc); readLoc = (readLoc+1) % BUFFER_SIZE; // move readLoc to next slot of Buffer output.append("\nReady to write to "+writeLoc+" and read from "+readLoc); printBuffer(output,sharedInt); // print current buffer contents if (writeLoc == readLoc) // Just emptied buffer { readable = false; output.append("\nBuffer empty\n"); } notifyAll(); // tell anyone waiting that something has happened return value; } // print contents of buffer so can see what is happening public void printBuffer(JTextArea out, int[] buf) { output.append("\nbuffer: "); for (int i = 0; i < buf.length; i++) //print contents of all slots in buffer out.append(" " + buf[i]); out.append("\n"); } }