/* 
 * BoundedBufferObs.java (Implements Producer and Consumer Using 
 *                        Event Notification).
 *
 * Written by : Nitin  Motgi (nmotgi@cs.ucf.edu)
 *
 * Portions copyright(c) 2000 to School of Electrical Engineering and 
 * Computer Science, UCF, Orlando.                   
 *
 * Use and distribution of this source code are strictly governed by 
 * terms and conditions set by the authors.
 * 
 * $Id : BoundedBufferObs.java, v1.0.0 02/07/2001. $
 *
 * Revision History Revisited:
*/

import java.util.*;
import java.lang.*;

/* Start of BoundedBufferObs.*/
public class BoundedBufferObs extends Observable{
     int nNumberOfProducers;            /* Tracks # of Producers.*/
     int nNumberOfConsumers;            /* Tracks # of Consumers.*/
     int nNumberOfSlots;                /* Number of Free Slots in Buffer */
     boolean bEndCondition;             /* End Condition for it.*/
     int nEvents;                       /* Basically # of items to be 
                                           produced.*/
     int nMaxSlots;

     ObsState State;

     long lStartTime,lStopTime;         /* Timers used to print messages
                                           during simulation.*/
     int nItem;
     int nNumberOfItemsProduced;        /* Tracks Events.*/
     int nNumberOfItemsConsumed;        /* Tracks Completed Events.*/
     Semaphore Block;

     

     /* Synchronization Mechanism.*/
     BoundedBufferPObs Producer[];      /* Array of Producers.*/
     BoundedBufferCObs Consumer[];      /* Array of Consumers.*/

     
     /* 
      * This function is constructor for this class.
      */
     public BoundedBufferObs(int nNumberOfProducer,
                             int nNumberOfConsumer,
                             int nNumberOfSlots,
                             int nEvents,
                             long lStartTime){

       /* Store them within this P/C controller.*/
       this.nNumberOfProducers = nNumberOfProducer;
       this.nNumberOfConsumers = nNumberOfConsumer;
       this.nMaxSlots          = nNumberOfSlots;
       this.nEvents           = nEvents;  
       this.lStartTime        = lStartTime;   
       this.nNumberOfSlots = 0;
       Block = new Semaphore(1);

       /* Initialise Items.*/
       nItem = 0;
       nNumberOfItemsProduced = 0;
       nNumberOfItemsConsumed = 0;
       State = new ObsState();

     }/* End of BoundedBufferSem.*/

     /*
      * This program is heart of this                            
      */
      public void Start(){
        /* Create all the producers and consumers.*/
        Producer = new BoundedBufferPObs[nNumberOfProducers];
        Consumer = new BoundedBufferCObs[nNumberOfConsumers];

        /* Print the Start Time.*/
        long lInterStartTime = System.currentTimeMillis();
        TimeFormat Time = new TimeFormat();
        System.out.println("Started using Monitors at time " + 
                           Time.formatTime(lInterStartTime - lStartTime));
                           
        /* Initialise their Environment.*/
        for(int nIndex=0; nIndex < nNumberOfProducers; nIndex++){
         Producer[nIndex] = new BoundedBufferPObs(nIndex+1,this);
         addObserver(Producer[nIndex]);
         Producer[nIndex].start();
        }/* End for.*/


        for(int nIndex=0; nIndex < nNumberOfConsumers; nIndex++){
         Consumer[nIndex] = new BoundedBufferCObs(nIndex+1,this);
         addObserver(Consumer[nIndex]);
         Consumer[nIndex].start();
        }/* End For.*/
        
        boolean bAllDead = false;
        while(bAllDead == false){
         bAllDead = true;
         for(int nIndex=0; nIndex < nNumberOfProducers; nIndex++){
          if(Producer[nIndex].isAlive() == true){ 
           bAllDead = false;
           break;
          }/* End if.*/
         }/* End for.*/

         for(int nIndex=0; nIndex < nNumberOfConsumers; nIndex++){
          if(Consumer[nIndex].isAlive() == true){ 
           bAllDead = false;
           break;
          }/* End if.*/
         }/* End for.*/
        }/* End While.*/

        lStopTime = System.currentTimeMillis();
        System.out.println("Completed using Monitors at time " + 
                           Time.formatTime(lStopTime - lStartTime));
        
      }/* End of Start.*/

      /*
       * Inserts an item in the Shared memory location. This shared
       * location is accessible by all the producers and consumers 
       * in the system.
       */
      public synchronized void Insert(){

       /* Check if Producer has exceeded number of events.*/
       if(nNumberOfItemsProduced == nEvents){
        /* Signal all the observers.*/
        State.Set(3);
        setChanged();
        notifyObservers((Object)State);
        return;
       }/* End if.*/
       
       /* Sync. this piece of code as it increments slots count which
          is shared by cosumer also.*/
       Block.P();
        /*If Slots filled, the signal no slots available.*/
        if(nNumberOfSlots == nMaxSlots){
          State.Set(1);
          setChanged();                 /* Notify the observers that
                                           buffer is full.*/
          notifyObservers((Object)State);        /* Hence, consumers can read
                                           in the data from the buffer.*/
          Block.V();
          return;
        }/* End if.*/
        nNumberOfSlots++;
       Block.V();                       /* Release lock.*/

       
       /* SIMULATES INSERT AN ITEM IN THE SHARED LOCATION.*/
       
       nNumberOfItemsProduced++;        /* Increment Item count.*/
       return;
     }/* End of Insert.*/

     /*
      * Gets the items from the shared memory location. This basically 
      * simulates picking of data.
     */
     public synchronized void Get(){

      /* Check if the total number of items produced by the producer
         are consumed.*/
      if(nNumberOfItemsConsumed >= nEvents){ 
       State.Set(4);
       setChanged();
       notifyObservers((Object)State);
       return;
      }/* End if.*/
       

       Block.P();
        if(nNumberOfSlots == 0){
          State.Set(2);
          setChanged();                    /* Notify the observers that
                                              buffer is full.*/
          notifyObservers((Object)State);  /* Hence, consumers can read
                                              in the data from the buffer.*/
       Block.V();
          
          return;
        }/* End if.*/
        nNumberOfSlots--;
       Block.V();
      


      /* SIMULATES GET ITEM FROM THE SHARED LOCATION.*/
      
      nNumberOfItemsConsumed++;
      return;
     }/* End of Get.*/

}/* End of BoundedBufferObs.*/

