Are Java do interruptions volatile?

If one thread interrupts another, will an interrupted status be detected immediately (i.e. it may have visibility problems)?

Also, I wonder, have you ever used breaks? Flying logic flag seems more reliable

+5
source share
1 answer

java do interruptions act volatile?

Based on reading javadocs, I would conclude that yes.

  • If the interrupted status does not have the “volatile like” semantics, there is no documented way to solve the (hypothetical) need to “happen earlier”. Without this, you could not be sure that interrupts would work. But they...

  • The interrupt status is not described in terms of reading and writing memory. Therefore, there is no reason to believe that the memory model is applied.

And, as it turned out, the interrupt behavior is specified in JLS 17.2.3 . Then, in JLS 17.4.4, interrupts are specifically referred to as defining the synchronization order:

"If thread T1 interrupts thread T2, the interrupt from T1 is synchronized to any point where any other thread (including T2) determines that T2 was interrupted (by throwing an InterruptedException or by calling Thread.interrupted or Thread.isInterrupted)."

Bottom line - The behavior of "volatile like" is guaranteed.


Also, I wonder, have you ever used breaks? Flying logic flag seems more reliable

Of course yes. Your conclusion that interrupts are unreliable is based on (IMO) the wrong mental model of how they are implemented. In addition, interrupts have special (and useful) behavior for target threads that are blocked in sleep or wait calls, etc.

The only significant drawback of interrupts is that they are indiscriminate. Any thread can interrupt any other. In contrast, if you use volatile boolean, you have more control over which threads can be “interrupted” by others (using access modifiers, using shared objects, etc.).

+7
source

Source: https://habr.com/ru/post/1213215/


All Articles