Skip to content

Instantly share code, notes, and snippets.

@njofce
Created March 24, 2020 15:10
Show Gist options
  • Select an option

  • Save njofce/a1c20fd1d83cd3f60b2bb2d82d3a4c06 to your computer and use it in GitHub Desktop.

Select an option

Save njofce/a1c20fd1d83cd3f60b2bb2d82d3a4c06 to your computer and use it in GitHub Desktop.
public class Buffer<T> {
List<T> items;
private int capacity;
private Lock canProduce = new ReentrantLock();
private Lock canConsume= new ReentrantLock();
public Buffer(int capacity){
this.items = new ArrayList<>(capacity);
this.capacity = capacity;
}
public synchronized T getItem() throws InterruptedException {
T item = null;
while(items.size() == 0)
wait();
item = items.remove(items.size() - 1);
notifyAll();
return item;
}
public synchronized void addItem(T item) throws InterruptedException {
while (items.size() == capacity)
wait();
items.add(item);
notifyAll();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment