Skip to content

Instantly share code, notes, and snippets.

@IvayloDankolov
Created April 28, 2016 01:25
Show Gist options
  • Save IvayloDankolov/999f8ebd262144f519003678c55ec533 to your computer and use it in GitHub Desktop.
Save IvayloDankolov/999f8ebd262144f519003678c55ec533 to your computer and use it in GitHub Desktop.
public class Exchanger<T> {
private T current;
private final ConditionVariable takeCond = new ConditionVariable();
private final ConditionVariable putCond = new ConditionVariable(true);
public T take() {
while(true) {
takeCond.block();
synchronized (this) {
if(current == null)
continue;
T res = current;
current = null;
takeCond.close();
putCond.open();
return res;
}
}
}
public void put(T val) {
while(true) {
putCond.block();
synchronized (this) {
if(current != null) {
continue;
}
current = val;
putCond.close();
takeCond.open();
return;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment