I am reading Google Guava RateLimiter. The acquire method will put thread to uninterruptible uninterruptible sleep while waiting for new permit. InterruptedException
The uninterruptible sleep doesn't totally ignore InterruptedException. But just catch it, remember that it has been interrupted and then continue sleep until reach timeout. It will finally set the interrupted flag back to the thread nicely.
List item
- This prevent caller to cancel the wait by interrupting. What might be the benefit of it? Is it just because the method doesn't what to force caller to handle InterruptedException?
- What are other use cases that we might want to use the same pattern of uninterruptible code?
Edit: I just realised I linked it to incorrect method.
public static boolean awaitUninterruptibly(Condition condition, long timeout, TimeUnit unit)
The correct method is sleepUninterruptibly.
public static void sleepUninterruptibly(long sleepFor, TimeUnit unit) {
boolean interrupted = false;
try {
long remainingNanos = unit.toNanos(sleepFor);
long end = System.nanoTime() + remainingNanos;
while (true) {
try {
// TimeUnit.sleep() treats negative timeouts just like zero.
NANOSECONDS.sleep(remainingNanos);
return;
} catch (InterruptedException e) {
interrupted = true;
remainingNanos = end - System.nanoTime();
}
}
} finally {
if (interrupted) {
Thread.currentThread().interrupt();
}
}
}