Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java: If statement in infinite while loop [duplicate]

I am new to Java and the following might be obvious, but it is puzzling to me. Consider the following code:

while(1>0){
  if(x!=0){
  //do something
  }
}

The x variable is changed in a different thread. However, the code in the if statement is never executed even when x is not zero. If I change the code by the following

while(1>0){
  System.out.println("here");

  if(x!=0){
  //do something
  }
}

the code in the if statement is now executed when x is no longer zero. I suspect this has to do with the rules of the Java compiler, but it is very confusing to me. Any help clarifying this would be greatly appreciated.

like image 921
Ivan Avatar asked Dec 27 '22 09:12

Ivan


1 Answers

If x is changing in a different thread then you are probably seeing a side-effect of the fact that you have not synchronized access to that variable.

The Java memory and threading model is pretty complex, so I'd recommend you get a copy of Java Concurrency in Practice by Brain Goetz and have a read.

The short answer is to make sure that access to x is enclosed in a synchronized block:

while (1 > 0) {
    int temp;
    synchronized (this) {
        temp = x;
    }
    if (temp != 0) {
        // Do something
    }
}

And similarly in the code that modifies x.

Note that this example stores x in a temporary variable, because you want synchronized blocks to be as small as possible - they enforce mutual exclusion locks so you don't want to do too much in there.

Alternatively, you could just declare x to be volatile, which will probably be sufficient for your use case. I'd suggest you go with the synchronized version because you'll eventually need to know how to use synchronized properly, so you might as well learn it now.

like image 164
Cameron Skinner Avatar answered Jan 27 '23 12:01

Cameron Skinner