my minecraft mod only works when i add System.out.println. is my code haunted 💀
ok so this is lowkey the weirdest bug ive ever had. im making a mod with a background thread that loads some stuff and the main thread waits for it to finish. works fine in my dev env but on my mates pc it just freezes forever. no crash no error nothing heres the important bits public class Loader { private boolean done = false; public void start() { new Thread(() -> { loadAllTheThings(); done = true; }).start(); }…
Accepted answer
Your program has a data race. The field is not volatile, so the JIT is allowed to assume it does not change inside the loop, hoist the read out, and spin forever. That is why it works on one machine and not another: it depends on when and how the loop gets compiled. System.out.println is synchronized internally. Taking and releasing that lock happens to make the thread see the new value, so the bug hides. It is not a fix. It is luck with extra steps. Fix, in order of preference: 1. Do not busy-wait at all. Use a CountDownLatch: countDown() in the worker, await() in the waiter. Or a CompletableFuture. 2. If you must keep the flag, declare it volatile. 3. In a game mod, never block the main thread waiting for anything. When loading finishes, schedule the result back onto the main thread. This is the Java Memory Model, chapter 17 of the language specification. Read it. Then learn C, where nobody will pretend this is safe for you. Regards.- the println fix is the programming version of turning it off and on again and it working