/**
 * BoundedBuffer.java
 *
 * This program implements the bounded buffer using shared memory.
 * Note that this solutions is NOT thread-safe. It will be used
 * to illustrate thread safety using Java synchronization in Chapter 7.
 *
 * @author Greg Gagne, Peter Galvin, Avi Silberschatz
 * @version 1.0 - July 15, 1999
 * Copyright 2000 by Greg Gagne, Peter Galvin, Avi Silberschatz
 * Applied Operating Systems Concepts - John Wiley and Sons, Inc.
 */

/**
* Adapted to the solution in Peter Galvin and Avi Silberschatz,
* Operating Systems Concepts, 5th edition, page 102 by Jalal Kawash
* May 2000.
*/


import java.util.*;
 
public class BoundedBuffer
{     
   public BoundedBuffer()
   {
      // buffer is initially empty
      in = 0;
      out = 0;
      
      buffer = new Object[BUFFER_SIZE];
   }

   // producer calls this method
   public void enter(Object item) {
      while (((in + 1) % BUFFER_SIZE) == out) 
         ; // do nothing
      
      // add an item to the buffer
      buffer[in] = item;
      in = (in + 1) % BUFFER_SIZE;

	if (((in + 1) % BUFFER_SIZE) == out)
                System.out.println("Producer Entered " + item + " Buffer FULL");
   }
   
   // consumer calls this method
   public Object remove() {
      Object item;
      
      while (in == out) 
         ; // do nothing
      
      // remove an item from the buffer
      item = buffer[out];
      out = (out + 1) % BUFFER_SIZE;

	if (in == out)
                System.out.println("Consumer Consumed " + item + " Buffer EMPTY");

      return item;
   }
   
   
   public static final int    NAP_TIME = 5;
   private static final int   BUFFER_SIZE = 3;
    
   private int in;   // points to the next free position in the buffer
   private int out;  // points to the next full position in the buffer
   private Object[] buffer;
}

