Advertisement
sci4me

Blocking Queue

Mar 10th, 2015
413
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.00 KB | None | 0 0
  1. public class BlockingQueue<T> {
  2.     private Queue<T> queue = new LinkedList<T>();
  3.     private int capacity;
  4.     private Lock lock = new ReentrantLock();
  5.     private Condition notFull = lock.newCondition();
  6.     private Condition notEmpty = lock.newCondition();
  7.  
  8.     public BlockingQueue(int capacity) {
  9.         this.capacity = capacity;
  10.     }
  11.  
  12.     public void put(T element) throws InterruptedException {
  13.         lock.lock();
  14.         try {
  15.             while(queue.size() == capacity) {
  16.                 notFull.await();
  17.             }
  18.  
  19.             queue.add(element);
  20.             notEmpty.signal();
  21.         } finally {
  22.             lock.unlock();
  23.         }
  24.     }
  25.  
  26.     public T take() throws InterruptedException {
  27.         lock.lock();
  28.         try {
  29.             while(queue.isEmpty()) {
  30.                 notEmpty.await();
  31.             }
  32.  
  33.             T item = queue.remove();
  34.             notFull.signal();
  35.             return item;
  36.         } finally {
  37.             lock.unlock();
  38.         }
  39.     }
  40. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement