I’m fairly new to Java and have a doubt that needs to be cleared.
Using code like this:
public int x;
public int elaborateX(){
x = 0;
setX();
x+=1;
return x;
}
public void setX(){
//...
//some workload here
//...
x = 5;
}
As I understand there are chances (especially if the method setX() does more than just set x ) that elaborateX() will return “1”.
I know after looking the issue around that Threads can be used to prevent the “bug”, but my question is; will the following always wait for setX() to be finish executing?
public int x;
public int elaborateX(){
x = 0;
if(setX()){
x+=1;
};
return x;
}
public boolean setX(){
//...
//some workload here
//...
x = 5;
return true;
}
Will elaborateX() always return “6” in this case?
I’m asking because I need to be 100% sure otherwise I will use the “proper approach” instead of this “trick”.
Thanks
There is no chance of it ever returning anything other than 6, unless you use multiple threads.
That’s what threads are about, every operation is threaded one after the other, there’s no reordering of operations. (At least nothing that you can see, the VM itself will do all sorts of crazy optimisations, but it must not be visible.)
However, Java uses short-circuit evaluation of boolean operators
||and&&, which although unrelated, can cause similar problems if you’re unprepared.