Okay so I have tested this code on java 8, 11, and 14, they all have the same result. This is bad practice and an unrealistic scenario, but I would like to understand the JVM internals that causes this to happen.
If you run this code you will notice that everything except the print part itself of system.out.println inside if execute. At some point with a slightly different java version I managed to get it to print by changing "play" too volatile, but even that doesn't work now.
Please at least test the code before claiming it is simply deadlocking the variables or using the cache, it is not, the if executes and everything inside it works except the print part itself.
public class Main { public static void main(String[] args) { TestClass t = new TestClass(); System.out.println("Starting test"); new MyRunnable(t).start(); while (true) t.testUpdate(System.currentTimeMillis()); } }
public class MyRunnable extends Thread { private TestClass t; public MyRunnable(TestClass t) { this.t = t; } @Override public void run() { try { Thread.sleep(500L); t.setPlay(true); } catch (InterruptedException e) { e.printStackTrace(); } } }
public class TestClass { private boolean play = false; private long lastUpdate = 0; private long updateRate = 2000; private boolean hasSysoBeenHit = false; public void testUpdate(long callTime) { System.out.println(play); System.out.println((callTime-lastUpdate)); if (this.play && ((callTime-lastUpdate) >= updateRate)) { System.out.println("Updating! " + (hasSysoBeenHit = true)); this.lastUpdate = callTime; } System.out.println("hasbeenhit? " + hasSysoBeenHit); } public void setPlay(boolean t) { System.out.println("Starting game..."); this.play = t; } }
https://stackoverflow.com/questions/65786752/system-out-mysteriously-disappears-although-the-code-line-executes January 19, 2021 at 02:56PM
没有评论:
发表评论