Skip to content

Instantly share code, notes, and snippets.

@IvayloDankolov
Created April 28, 2016 01:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • 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