Question

I'm currently running a separate task in a Java Swingworker, and here is the code (edited for clarity):

while (true) {
    while (value == 0) {
        value = utils.getValue();
        System.out.println("Value is zero");
    }
    System.out.println("Value isn't zero, out of loop");
}

This code runs perfectly fine. However, if I remove the println("Value is zero"), nothing happens, and the loop is never exited. Another thread is handling the population of the value, which gets updated roughly 5 seconds after the program starting.

I'm a little confused as to why the code only executes if there is a println in there. Can anyone shine any light on this?

Was it helpful?

Solution 2

My best guess: add some sleep condition to give the other thread time to populate the result. In your question you say it takes about 5 seconds; this might take (way) longer when you add a busy-wait loop (while true).

try:

while (true) {
    while (value == 0) {
        value = utils.getValue();
        try {
            Thread.sleep(500);
        }
        catch (InterruptedException e) {
        }
        System.out.println("Value is zero");
    }
    System.out.println("Value isn't zero, out of loop");
}

OTHER TIPS

  • Long answer, read this.
  • Short answer, the value a thread stores in the heap may have been cached by other threads and if you don't synchronize them the resulting behavior may be surprising. It may be hard to know what happens and why. Access shared variables with synchronization or store shared values inside 'atomic' objects or 'volatile' variables.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top