Is atomic interrupt checking in java?

If you use the following "interrupt" idiom 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, the interrupt cannot be ignored if the interrupt "arrives" between check Thread.currentThread().isInterrupted() and call queue.take() ? Is this not a validation than action operation? If so, is there any way to guarantee that the loop is left in any case if the thread is interrupted?

You can use polling with a timeout so that the cycle remains after the timeout , but is it possible to check the interrupted status and act on it atomically?

+7
java multithreading concurrency interrupt
source share
3 answers

I would change 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 immediately throw an InterruptedException if the thread is interrupted and at the same time exits the while loop.

+3
source share

Only a call can clear and then an interrupted flag, so nothing can happen between isInterrupted and queue.take ().

0
source share

but is it possible to check the state of interruption and act on it atomically

Well, I donโ€™t know what you mean โ€œatomicallyโ€ here. Can we assume that you want something like onInterrupt (...)?

Interrupts are designed to โ€œinterruptโ€ a stream, so all I / O operations by default raise an InterruptedException, which you can catch or check. This allows threads to stop gracefully closing / releasing any blocked resources.

As an event handler , you might want to implement an undoable task where you can handle your own undo events (well, not the default JRE interrupt).

0
source share

All Articles