Source of SynchronizedBuffer.java


  1: // Fig. 23.19: SynchronizedBuffer.java
  2: // SynchronizedBuffer synchronizes access to a single shared integer.
  3: 
  4: public class SynchronizedBuffer implements Buffer
  5: {
  6:    private int buffer = -1; // shared by producer and consumer threads
  7:    private boolean occupied = false; // count of occupied buffers
  8:    
  9:    // place value into buffer
 10:    public synchronized void set( int value )
 11:    {
 12:       // while there are no empty locations, place thread in waiting state
 13:       while ( occupied ) 
 14:       {
 15:          // output thread information and buffer information, then wait
 16:          try 
 17:          {
 18:             System.out.println( "Producer tries to write." );
 19:             displayState( "Buffer full. Producer waits." );
 20:             wait();
 21:          } // end try
 22:          catch ( InterruptedException exception ) 
 23:          {
 24:             exception.printStackTrace();
 25:          } // end catch
 26:       } // end while
 27:         
 28:       buffer = value; // set new buffer value
 29:         
 30:       // indicate producer cannot store another value
 31:       // until consumer retrieves current buffer value
 32:       occupied = true;
 33:         
 34:       displayState( "Producer writes " + buffer );
 35:       
 36:       notify(); // tell waiting thread to enter runnable state
 37:    } // end method set; releases lock on SynchronizedBuffer 
 38:     
 39:    // return value from buffer
 40:    public synchronized int get()
 41:    {
 42:       // while no data to read, place thread in waiting state
 43:       while ( !occupied )
 44:       {
 45:          // output thread information and buffer information, then wait
 46:          try 
 47:          {
 48:             System.out.println( "Consumer tries to read." );
 49:             displayState( "Buffer empty. Consumer waits." );
 50:             wait();
 51:          } // end try
 52:          catch ( InterruptedException exception ) 
 53:          {
 54:             exception.printStackTrace();
 55:          } // end catch
 56:       } // end while
 57: 
 58:       // indicate that producer can store another value 
 59:       // because consumer just retrieved buffer value
 60:       occupied = false;
 61: 
 62:       int readValue = buffer; // store value in buffer
 63:       displayState( "Consumer reads " + readValue );
 64:       
 65:       notify(); // tell waiting thread to enter runnable state
 66: 
 67:       return readValue;
 68:    } // end method get; releases lock on SynchronizedBuffer 
 69:     
 70:    // display current operation and buffer state
 71:    public void displayState( String operation )
 72:    {
 73:       System.out.printf( "%-40s%d\t\t%b\n\n", operation, buffer, 
 74:          occupied );
 75:    } // end method displayState
 76: } // end class SynchronizedBuffer