Skip to content

Instantly share code, notes, and snippets.

@jhalterman
Created November 4, 2013 21:02
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 jhalterman/7309165 to your computer and use it in GitHub Desktop.
Save jhalterman/7309165 to your computer and use it in GitHub Desktop.
A waiter where waiting threads can be interrupted (as opposed to awakened).
/**
* A waiter where waiting threads can be interrupted (as opposed to awakened).
*
* @author Jonathan Halterman
*/
public class InterruptableWaiter {
private final Sync sync = new Sync();
private static final class Sync extends AbstractQueuedSynchronizer {
private static final long serialVersionUID = 4016766900138538852L;
@Override
protected int tryAcquireShared(int acquires) {
// Disallow acquisition
return -1;
}
}
/**
* Waits forever, aborting if interrupted.
*/
public void await() throws InterruptedException {
sync.acquireSharedInterruptibly(0);
}
/**
* Waits for the {@code waitDuration}, aborting if interrupted.
*/
public void await(Duration waitDuration) throws InterruptedException {
sync.tryAcquireSharedNanos(0, waitDuration.toNanos());
}
/**
* Interrupts waiting threads.
*/
public void interruptWaiters() {
for (Thread t : sync.getSharedQueuedThreads())
t.interrupt();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment