If using following "idiom" with interruption in Java, for example from this answer.
while (!Thread.currentThread().isInterrupted()) {
try {
Object value = queue.take();
handle(value);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}
Where take is a blocking operation, can an interrupt not be ignored for the time being if an interrupt "arrives" between the check of Thread.currentThread().isInterrupted()
and the call queue.take()
? Is this not a "check-than-act" operation? If so, can it somehow be guaranteed that the loop is left in any case if the thread is interrupted?
It is possible to use poll with a timeout so that the loop is left after the timeout, but is it possible to check the interrupted status and act on it atomically?
I would swap the try/catch and while loop:
try {
while (true) {
Object value = queue.take();
handle(value);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
The take()
operation will throw an InterruptedException
immediately if the thread is interrupted, and at the same time break out of the while loop.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With