-
-
Save IvayloDankolov/999f8ebd262144f519003678c55ec533 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
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