If one thread interrupts another, will the interrupted status be immediately visible (i.e can it have visibility problems)?
On top of that I am wondering do you ever use interruptions? A Volatile boolean flag seems way more reliable
In Java Threads, if any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the interrupt() method on the thread, breaks out the sleeping or waiting state throwing InterruptedException.
An interrupt is an indication to a thread that it should stop what it is doing and do something else. It's up to the programmer to decide exactly how a thread responds to an interrupt, but it is very common for the thread to terminate.
interrupt() does not interrupt the thread, it continues to run.
Using volatile is yet another way (like synchronized, atomic wrapper) of making class thread-safe. Thread-safe means that a method or class instance can be used by multiple threads at the same time without any problem.
java do interruptions act volatile?
Based on a reading of the javadocs I would infer the answer is yes.
If the interrupted status doesn't have "volatile like" semantics, there is no documented way to address the (hypothetical) need for a "happens before". Without that, you couldn't be sure that interrupts would work. But they do ...
The interrupt status is not described in terms of memory reads and writes. Hence, there is no reason to infer that the memory model applies.
And, as it turns out, the behavior of interrupts is specified in JLS 17.2.3. Then in JLS 17.4.4, interrupts are specifically mentioned as defining a synchronization order:
"If thread T1 interrupts thread T2, the interrupt by T1 synchronizes-with any point where any other thread (including T2) determines that T2 has been interrupted (by having an InterruptedException thrown or by invoking Thread.interrupted or Thread.isInterrupted)."
Bottom line - "volatile like" behavior is guaranteed.
On top of that I am wondering do you ever use interruptions? A Volatile boolean flag seems way more reliable
Sure, I do. Your inference that interrupts are unreliable is based on (IMO) an incorrect mental model of how they are implemented. Besides, interrupts have special (and useful) behavior for target threads that are blocked in sleep
or wait
calls, and so on.
The only significant downside of interrupts is that they are indiscriminate. Any thread can interrupt any other one. By contrast, if you are using a volatile boolean you have more control over which threads can "interrupt" which other ones (via access modifiers, use of shared objects, etc).
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