Reordering Effects
We'll cover the following...
Introduction
As discussed earlier the JMM allows for reordering of statements in the program order as long as the outcome of the program isn’t altered. Consider the program below and try to come up with all the possible outcomes the program can have:
Example 1
The above program is adapted from an example in JSR-133. The program has two variables that are shared between two threads sharedA and sharedB. Each thread updates one of the shared variables that is used in the other thread. To keep the example simple, we can boil down the execution of the two threads as follows:
| Instruction# | Thread1 | Thread2 |
|---|---|---|
| 1. | localA = sharedA; | localB = sharedB; |
| 2. | sharedB = 1; | sharedA = 2; |
Most folks would come up with the following possible outcomes:
-
localA=0andlocalB=1 -
localA=2andlocalB=0 -
localA=0andlocalB=0
However, it might surprise many but the program can very well print localA=2 and localB=1! How is that even possible? Think from the point of view of a compiler, it sees the following instructions for method1():
...