I'm having problems understanding how JMM relates to possible instructions reordering. For example, let's consider the following code snippet:
volatile boolean t1HasArrived = false, t2HasArrived = false; // In thread 1 t1HasArrived = true; while (!t2HasArrived) ; // In thread 2 t2HasArrived = true; while (!t1HasArrived) ; Now, I want to believe that this code implements Barrier synchronization for two threads. But I'm not sure about it. The thing that gives me doubts is read/writes reordering: is there anything in JMM that would prevent compiler or CPU to rearrange execution path of the code like the code snippet below? And if not, how do you actually prove that such reordering is allowed?
// In thread 1 while (!t2HasArrived) ; t1HasArrived = true; // In thread 2 while (!t1HasArrived) ; t2HasArrived = true; Note, that I'm not trying to implement locks-free Barrier. This is just an example that came to my mind after I started thinking about instructions reordering. I just want to understand how to apply JMM rules to it. It is relatively easy to reason about piece of code when there is only one volatile variable/lock involved, but when there are several, things become complicated.