Noncancelable Task that Restores Interruption Before Exit
I was reading some java thread interruption and I don't understand some stuff. Hope someone will explain me. So, it's done the following code
public Integer getInteger(BlockingQueue<Integer> queue) {
boolean interrupted = false;
try {
while (true) {
try {
return queue.take();
} catch (InterruptedException e) {
interrupted = true;
// fall through and retry
}
}
} finally {
if (interrupted)
Thread.currentThread().interrupt(开发者_运维问答);
}
}
The explanation is as follows :
Activities that do not support cancellation but still call interruptible blocking methods will have to call them in a loop, retrying when interruption is detected. In this case, they should save the interruption status locally and restore it just before returning, as shown in listing. rather than immediately upon catching InterruptedException. Setting the interrupted status too early could result in an infinite loop, because most interruptible blocking methods check the interrupted status on entry and throw InterruptedException immediately if it is set. (Interruptible methods usually poll for interruption before blocking or doing any significant work, so as to be as responsive to interruption as possible.)
I don't understand why we should save the interrupted status locally.
I would be glad to hear some explanation.By the design the method could not ever throw the InterruptedException. So it means we always expect take a value from the queue. But somebody could want the thread to be interrupted, that's why we have to save-restore the interrupted state after we have finally took a value from the queue.
So, the thread get finished only after taking a value from the queue.
UPDATE: Look into the take()
method implementation. It has the following as the first statements:
public final void acquireInterruptibly(int arg) throws InterruptedException {
if (Thread.interrupted())
throw new InterruptedException();
...
}
The loop will finish because of the statement
return queue.take();
This is not a tight loop even though it looks like one. It just blocks for one element and and returns as soon as it is available and retries if an interruption occurs.
精彩评论