Created
March 24, 2020 16:18
-
-
Save njofce/5123e9256c45606a2dc32836fb57b881 to your computer and use it in GitHub Desktop.
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
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