Skip to content

Instantly share code, notes, and snippets.

@andriybuday
Created February 8, 2020 03:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save andriybuday/98e279c8c7c1ac24844d8be696b42f4c to your computer and use it in GitHub Desktop.
Save andriybuday/98e279c8c7c1ac24844d8be696b42f4c to your computer and use it in GitHub Desktop.
BoundedBlockingQueue
public class BoundedBlockingQueue {
private Deque<Integer> queue;
private Semaphore enqueue;
private Semaphore dequeue;
public BoundedBlockingQueue(int capacity) {
queue = new ConcurrentLinkedDeque<>();
enqueue = new Semaphore(capacity);
dequeue = new Semaphore(0);
}
public void enqueue(int element) throws InterruptedException {
enqueue.acquire();
queue.add(element);
dequeue.release();
}
public int dequeue() throws InterruptedException {
dequeue.acquire();
int val = queue.poll();
enqueue.release();
return val;
}
public int size() {
return queue.size();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment