Skip to content

Instantly share code, notes, and snippets.

@njofce
Created March 24, 2020 16:18
Show Gist options
  • Save njofce/5123e9256c45606a2dc32836fb57b881 to your computer and use it in GitHub Desktop.
Save njofce/5123e9256c45606a2dc32836fb57b881 to your computer and use it in GitHub Desktop.
class Buffer<T> {
List<T> items;
private int capacity;
private Semaphore consumeSemaphore = new Semaphore(0);
private Semaphore produceSemaphore = new Semaphore(1);
private Semaphore pcCoordinatorSemaphore = new Semaphore(1);
Buffer(int capacity) {
this.items = new ArrayList<>(capacity);
this.capacity = capacity;
}
T getItem() throws InterruptedException {
T item = null;
consumeSemaphore.acquire();
pcCoordinatorSemaphore.acquire();
while (items.size() == 0) {
pcCoordinatorSemaphore.release();
Thread.sleep(100);
pcCoordinatorSemaphore.acquire();
}
item = items.remove(items.size() - 1);
pcCoordinatorSemaphore.release();
produceSemaphore.release();
return item;
}
void addItem(T item) throws InterruptedException {
produceSemaphore.acquire();
pcCoordinatorSemaphore.acquire();
while (items.size() > capacity) {
pcCoordinatorSemaphore.release();
Thread.sleep(100);
pcCoordinatorSemaphore.acquire();
}
items.add(item);
pcCoordinatorSemaphore.release();
consumeSemaphore.release();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment