Looks like the boolean start
is being updated by another thread but you didn't declare it as volatile
, so the loop never looks at the updated value.
"Fixing" it by adding the println is just a wierd consequence of the way JVM manages the thread's stack state when it goes to acquire the native system object for the console printer. The fix is to make start volatile and/or synchronize around accessing it.
SCCE:
Never prints:
public class Testit {
public static void main(String[] args) {
busted t = new busted();
t.start();
try {
Thread.sleep(1000L);
} catch (Exception e) {}
t.startUpdating();
}
public static class busted extends Thread {
private boolean start = false;
public void startUpdating() {
start = true;
}
@Override
public void run() {
updateTimeElapsedIndefinitely();
}
public void updateTimeElapsedIndefinitely() {
while (true) {
if (start) {
System.out.println("Hello");
}
}
}
}
}
Starts spamming Hello after 1 second by changing to this:
private volatile boolean start = false;