Skip to content

Instantly share code, notes, and snippets.

@pratapaditya1997
Created July 8, 2020 16:18
Show Gist options
  • Save pratapaditya1997/8ebd6978083f512c2fcc7061ccd15468 to your computer and use it in GitHub Desktop.
Save pratapaditya1997/8ebd6978083f512c2fcc7061ccd15468 to your computer and use it in GitHub Desktop.
Blocking Queue implementation
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