Let's take following statements:
int d0, d1;
int[] ds = {0, 0};
Now one thread has following instructions:
d0++;
d1++;
while the other thread has this instruction:
ds[1] = d1;
ds[0] = d0;
If we run these threads in parallel, there are obviously three combinations that ds
can look like: {0, 0}, {1, 1}, and {1, 0}.
Now the big question is: Can there also be {0, 1}? Can the Compiler/JVM simply swap instruction because it thinks they are unrelated? If yes, what exactly are the "rules" for such behaviour and is it up to the compiler or the JVM?
Yes, {0, 1}
is also possible. The Java memory model is not strong enough to guarantee ordering in this case. This doesn't even require instruction reordering -- this will happen anyway if you run the program on anything but x86 or x86_64.
To be clear here, the actual CPU hardware will reorder these loads and stores, just not if it's an x86.
See the Java Memory Model FAQ
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With