This question is from an example from the book "Java concurrency in Practice" by Brian Goetz, Chapter 7 , 7.1.3 Responding to interruption (page 143 - 144) It says in the book
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 example below, rather than immediately upon catching InterruptedException. Setting the interrupted status too ealry 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......
public Task getNextTask(BlockingQueue<Task> queue) {
boolean interrupted = false;
try {
while (true) {
try {
return queue.take();
} catch (InterruptedException e) {
interrrupted = true;
}
}
} finally {
if (interrupted)
Thread.currentThread().interrupt();
}
}
My question is why is the loop required?
Also if queue.take() throws an interruptedException then I am assuming the interrupt flag is set on the current thread correct? Then the next call to queue.take() will again throw interruptedException since the previous interrupt on current thread is not cleared and will this not cause an infinite loop?