Advertisement
Guest User

Untitled

a guest
Feb 16th, 2019
81
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 0.93 KB | None | 0 0
  1. import java.util.*;
  2. import java.util.concurrent.Semaphore;
  3. import java.lang.Object;
  4. import java.nio.Buffer;
  5.  
  6. public class BoundedBuffer<E> implements Buffer<E>
  7. {
  8.     private static final int BUFFER_SIZE=5;
  9.     private E[] buffer;
  10.     private int in, out;
  11.     private Semaphore mutex;
  12.     private Semaphore empty;
  13.     private Semaphore full;
  14.  
  15.     public BoundedBuffer()
  16.     {
  17.         //buffer is initially empty
  18.         in=0;
  19.         out=0;
  20.         mutex= new Semaphore(1);
  21.         empty= new Semaphore(BUFFER_SIZE);
  22.         full=new Semaphore(0);
  23.  
  24.         buffer=(E[]) new Object[BUFFER_SIZE];
  25.  
  26.     }
  27.  
  28.     public void insert(E item)
  29.     {
  30.         empty.acquire();
  31.         mutex.acquire();
  32.  
  33.         //add item
  34.         buffer[in]=item;
  35.         in=(in+1)%BUFFER_SIZE;
  36.  
  37.         mutex.release();
  38.         full.release();
  39.     }
  40.  
  41.     public E remove()
  42.     {
  43.         E item;
  44.  
  45.         full.acquire();
  46.         mutex.acquire();
  47.  
  48.         //remove item
  49.         item=buffer[out];
  50.         out=(out+1)%BUFFER_SIZE;
  51.  
  52.         mutex.release();
  53.         empty.release();
  54.  
  55.         return item;
  56.     }
  57. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement