"Java Memory Model (JMM) defines a partial ordering called
happens-before on all actions with the program. Actions are reads and writes to variables, locks and unlocks of monitors etc. To guarantee that the thread executing action B can see the results of action A, there must be happens before relationship between A and B. In the absence of
happens-before ordering between two operations, the JVM is free to re-order them as it pleases (due to the fact that every processor has it's cache and it needs to flush to the main memory). A correctly synchronized program is one with no data races, correctly synchronized programs exhibits sequential consistency, meaning that all actions within the program appear to happen in a fixed, global order.
The rules for
happens-before are:
Program order rule. Each action in a thread
happens-before every action in that thread that comes later in the program order.
Monitor lock rule. An unlock on a monitor lock
happens-before every subsequent lock on that same monitor lock.
Volatile variable rule. A write to a volatile field
happens-before every subsequent read of that same field.
Thread start rule. A call to Thread.start on a thread
happens-before any other rhread detects taht thread has terminated, either by successfully return from Thread.join or by Thread.isAlive returning false.
Interruption rule. A thread calling interrupt on another thread
happens-before the interrupted thread detects the interrupt( either by having InterruptedException thrown, or invoking isInterrupted or interrupted).
Finalizer rule. The end of a constrcutor for an object
happens-before the start of the finalizer for that obejct.
Transitivity. If A
happens-before B, and B
happens-before C, then A
happens-before C.
"
Ref: Java Concurrency in Pratice