001    //package edu.unima.ky.parallel;
002    
003    /** 
004      * Bounded buffer. 
005      * @author Akitoshi Yoshida
006      * @author Heinz Kredel. 
007      */ 
008    public class BoundedBuffer extends Object {
009    
010      /** 
011        * The buffer storage of objects.
012        */ 
013      private Object[] buffer;
014    
015      /** 
016        * The size of the buffer.
017        */
018      private int size;
019    
020      /** 
021        * The position of the first filled cell. 
022        */ 
023     private int front;
024    
025      /** 
026        * The position of the first empty cell. 
027        */ 
028      private int rear;
029    
030      /** 
031        * A semaphore to indicate an empty buffer. 
032        */ 
033      private Sema empty;
034    
035      /** 
036        * A semaphore to indicate a full buffer.
037        */ 
038      private Sema full;
039    
040      private Object pt;
041      private Object gt;
042    
043      /**
044        * Constructs a BoundedBuffer with a desired size. 
045        * @param init the size of the buffer.
046        */
047      public BoundedBuffer(int init) {
048        buffer = new Object[init];
049        size = init;
050        front = 0;
051        rear = 0;
052        empty = new Sema(init);
053        full = new Sema(0);
054        pt = new Object();
055        gt = new Object();
056      }
057    
058    
059      /**
060        * Tests if the BoundedBuffer is empty. 
061        * If it is, gives back the value true.
062        * @return The boolean value of
063             (whether the BoundedBuffer is empty or not).   
064        */
065      public boolean empty() {
066        return (front == rear);
067      }
068    
069    
070      /**
071       * Put an object to the BoundedBuffer.
072       * @param v an object to be put to the buffer.
073       */
074      public void put(Object v) {
075        empty.P();
076        synchronized (pt) {
077          if (rear >= size) rear -= size;
078          buffer[ rear ] = v; 
079          rear++;     
080        }
081        full.V();
082      }
083    
084      /**
085       * Get an object from the BoundedBuffer.
086       */
087      public Object get() {
088        Object v;
089        full.P();
090        synchronized (gt) {
091          if (front >= size) front -= size;
092          v = buffer[ front ]; 
093          front++; 
094        }
095        empty.V();
096        return v;
097      }
098    }