Skip to content

Instantly share code, notes, and snippets.

@franz1981
Created May 25, 2023 12:47
Show Gist options
  • Save franz1981/03d69f71dd594c6e57d7c9baf280569f to your computer and use it in GitHub Desktop.
Save franz1981/03d69f71dd594c6e57d7c9baf280569f to your computer and use it in GitHub Desktop.
public class JCTools {
private volatile Thread sleeping;
<T> void add(Queue<? super T> q, T e) {
while (!q.offer(e)) {
// TODO: FIXME - cannot happen in production (even if is what some does!)
LockSupport.parkNanos(1L);
}
LockSupport.unpark(sleeping);
}
<T> T take(Queue<? extends T> q) {
for (; ; ) {
T e = q.poll();
if (e != null) {
return e;
}
sleeping = Thread.currentThread();
try {
e = q.poll();
if (e != null) {
return e;
}
LockSupport.park();
// can spuriously wakeup!
} finally {
sleeping = null;
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment