Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is an "atomic" interrupt check possible in java?

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?

like image 388
user140547 Avatar asked Jun 10 '16 07:06

user140547


1 Answers

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.

like image 62
Andy Turner Avatar answered Sep 21 '22 10:09

Andy Turner