Skip to content

Instantly share code, notes, and snippets.

@thomasnield
Created May 26, 2016 15:08
Show Gist options
  • Save thomasnield/2d07d2324159aa5debd714759d7e7876 to your computer and use it in GitHub Desktop.
Save thomasnield/2d07d2324159aa5debd714759d7e7876 to your computer and use it in GitHub Desktop.
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