Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can a Java Compiler or JVM swap instruction order of independent instructions?

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?

like image 602
Danyel Avatar asked Feb 19 '23 11:02

Danyel


1 Answers

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

like image 80
Dietrich Epp Avatar answered Feb 21 '23 01:02

Dietrich Epp