Created
February 8, 2020 03:39
-
-
Save andriybuday/98e279c8c7c1ac24844d8be696b42f4c to your computer and use it in GitHub Desktop.
BoundedBlockingQueue
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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