Created
May 26, 2016 15:08
-
-
Save thomasnield/2d07d2324159aa5debd714759d7e7876 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
import java.util.concurrent.Semaphore; | |
public final class SingleBlockingQueue<T> { | |
private volatile T value; | |
private final Semaphore full = new Semaphore(0); | |
private final Semaphore empty = new Semaphore(1); | |
private volatile boolean hasValue = false; | |
public void offer(T value) throws InterruptedException { | |
empty.acquire(); | |
this.value = value; | |
hasValue = true; | |
full.release(); | |
} | |
public T take() throws InterruptedException { | |
full.acquire(); | |
T returnValue = value; | |
value = null; // Should release reference | |
hasValue = false; | |
empty.release(); | |
return returnValue; | |
} | |
public boolean hasValue() { | |
return hasValue; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment