Reordering Effects

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:

Press + to interact
class ReorderingExample {
// shared variables
int sharedA = 0;
int sharedB = 0;
// executed by thread1
void method1() {
int localA;
localA = sharedA;
sharedB = 1;
System.out.println("localA = " + localA);
}
// executed by thread2
void method2() {
int localB;
localB= sharedB;
sharedA = 2;
System.out.println("localB = " + localB);
}
public static void main(String[] args) throws InterruptedException {
final ReorderingExample reorderingExample = new ReorderingExample();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
reorderingExample.method1();
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
reorderingExample.method2();
}
});
thread1.start();
thread2.start();
thread1.join();
thread2.join();
}
}

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=0 and localB=1

  • localA=2 and localB=0

  • localA=0 and ...