Search code examples
javamultithreadingconcurrencyvolatilehappens-before

Do I have the correct understanding of Can Reorder rules from the JSR-133 Cookbook?


In this link http://gee.cs.oswego.edu/dl/jmm/cookbook.html , there is this table that speaks about what can be reordered and cannot.

Here is the image

enter image description here

Now take a look at this quote from http://tutorials.jenkov.com/java-concurrency/volatile.html

"Instructions before and after can be reordered, but the volatile read or write cannot be mixed with these instructions."

So for example say I had the code

int x = 5; 
int z = 2; // storing 2 into z
z = someVolatileIntNotTwo; // storing some volatile int that != 2 into z
int a = 6; 
System.out.println(z);

From what the table is telling me, it is saying that a normal store and a volatile load can be reordered which means that

int z = 2; // storing 2 into z
z = someVolatileIntNotTwo; // storing some volatile int that != 2 into z

can be reordered to

z = someVolatileIntNotTwo; // storing some volatile int that != 2 into z
int z = 2; // storing 2 into z

which can mean that the program will print something other than 2 in the case of reordering.

The reasoning behind this is that first z = 2 is doing a normal store, then z = someVolatileIntNotTwo is doing a volatile load followed by a normal store. While it is true that a volatile load followed by a normal store cannot be reordered, in this case this is not happening since we still get this sequence if reordered.

z = someVolatileIntNotTwo; // volatile Load then normal Store. 
int z = 2; // normal load

there is no case where the 1st operation is reordered with the 2nd operation other than the normal load(int z = 2) and [volatile load and normal store](z = someVolatileIntNotTwo) being reordered which according to the table is fine

However, jenkov tutorials says this is not possible. So, who is right?


Solution

  • Your interpretation of the scope of reorderings is too broad. From the JSR-133 Cookbook:

    even though the table doesn't say so, you can't reorder a load with a subsequent store to the same location.

    To answer your question more directly: neither article is incorrect. The reordering in your sample is illegal.