Created
July 8, 2020 16:18
-
-
Save pratapaditya1997/8ebd6978083f512c2fcc7061ccd15468 to your computer and use it in GitHub Desktop.
Blocking Queue implementation
This file contains hidden or 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
import java.util.*; | |
public class BlockingQueue<T> { | |
private Queue<T> queue = new LinkedList<T>(); | |
private int capacity = 10; //default capacity is 10 | |
BlockingQueue() {} | |
BlockingQueue(int capacity) { | |
this.capacity = capacity; | |
} | |
// add element at the end of the queue | |
public synchronized void add(T elem) throws InterruptedException { | |
while(queue.size() == capacity) { | |
wait(); | |
} | |
queue.add(elem); | |
if(queue.size() == 1) { | |
notifyAll(); | |
} | |
} | |
// removes first element in the queue | |
public synchronized T remove() throws InterruptedException { | |
while(queue.size() == 0) { | |
wait(); | |
} | |
if(queue.size() == capacity) { | |
notifyAll(); | |
} | |
T removedElement = queue.remove(); | |
return removedElement; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment