Created
November 4, 2013 21:02
-
-
Save jhalterman/7309165 to your computer and use it in GitHub Desktop.
A waiter where waiting threads can be interrupted (as opposed to awakened).
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
/** | |
* 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