In other words I want to know if changing variable before interrupt is always visible when interrupt is detected inside interrupted thread. E.g.
private int sharedVariable;
public static void interruptTest() {
Thread someThread = new Thread(() -> {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// Is it here guaranteed that changes before interrupt are always visible here?
System.out.println(sharedVariable);
}
});
someThread.start();
Thread.sleep(1000);
sharedVariable = 10;
someThread.interrupt();
}
I tried to find answer in Java language specification and in
Summary page of the java.util.concurrent package mentioned in Java tutorial but interrupt
was not mentioned.
I know about volatile
and other synchronize primitives but do I need them?
Yes, interrupting a thread T2 from a thread T1 creates a happens-before relationship between T1 and T2, as described in the JLS 17.4.4. Synchronization Order:
Now that only implies that T1 synchronizes-with the detection of the interrupt T2, while you asked about happens-before. Luckily the former implies the latter from 17.4.5. Happens-before Order:
So you are safe to access
sharedVariable
knowing that it has (at least) the value written by T1, even withoutvolatile
.