I have the following class:
public class ThreadStopTest {
private static boolean enabled = true;
private static int milliseconds = 5;
public static void main(String[] args) {
new Thread(ThreadStopTest::process).start();
sleepMillSeconds(milliseconds);
disableProcessing();
}
private static void disableProcessing() {
enabled = false;
System.err.println("Processing disable called");
}
private static boolean isEnabled() {
return enabled;
}
private static void process() {
boolean printed = false;
while (isEnabled()) {
if(!printed) {
System.err.println("Processing started");
printed = true;
}
}
System.err.println("Processing finished");
}
private static void sleepMillSeconds(int mills) {
try {
Thread.sleep(mills);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
In case if milliseconds > 5, this class execution hangs and never stops, but if milliseconds <=5, then the program runs and completes successfully.
Adding a volatile modifier to the enabled parameter solves the problem, but I'd like to know what is the reason for this weird behavior. Did anyone get ideas?