I have the following code :
boolean running = true;
while (running) {
MathStackJPanel focused = Main.frame.mainPanel.focused;
//System.out.print("");
if (focused != null) {
Point p = focused.getMousePosition();
ExpressionComponent ep = focused.getUnderPoint(p);
}
}
focused.getUnderPoint(p)
is supposed to print something (for debugging) but does not. As soon as I uncomment System.out.print("")
, the code works as intended and I see things printed in the console (from focused.getUnderPoint(p)
). Why does that simple line that is supposed to literally do nothing totally modify the behavior of my code ? Also, I can tell that the code inside the while loop is not being run AT ALL because when I uncomment System.out.print("")
an exception is thrown (as expected), in a certain scenario.
Does java optimize away my while loop even though it shouldn't ?
Someone asked for a better example :
public static Object b = null;
public static void a() {
System.out.println("OK");
}
public static void main(String[] args) {
Thread thread = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
b = 4;
});
thread.start();
while (true) {
//System.out.print("");
if (b != null) {
a();
}
}
}
Uncomment the line to make it work (prints ok)