I’m getting a very strange error. I have the following code:
while (true) {
System.out.println(model.getLightState());
if (model.getLightState() == 1) {
System.out.println("Entered..");
view.driveThroughJunction();
break;
}
}
Now, my program enters the if statement when the light state changes to ‘1’ and executes the code that’s fine. But this ONLY works if I have that print out statement after the while loop is entered. I find that weird. Will a ‘sysout’ line have any effect on the if statement? Apparently it does for the above case.
Any ideas to why this is ?
EDIT:
(in the model class)
public final byte getLightState() {
return lightChanger.getLightValue();
}
(in lightchanger class)
public byte getLightValue() {
return light.getState();
}
(in the light class)
public final byte getState() {
return this.state;
}
You have a synchronization problem, leading to a visibility problem. If no synchronization is used when reading and writing a variable shared by multiple threads, there is no guarantee that the value written by one thread is visible to other threads.
To fix that you need to do one of those things:
statefieldvolatilestatefield type toAtomicIntegerstatefield (using thesynchronizedkeyword), using the same lock every time, of course.Your sysout call makes the value visible because it internally calls some method that flushes the state of the registers to the main memory (by writing to a volatile field or calling a synchronized method, for example).