Understanding Happens-before
Memo, please indicate the error.
HB Rule
Multithreading has two basic issues, atomicity and visibility, while happens-before rules are used to address visibility issues :
In time, action a takes place before action B, so B is guaranteed to see a?
Note: Do not consider the order rearrangement, because the reflow effect should be consistent before the rearrangement
If the answer to the above question is "Yes," then you can say HB (A, B)
The JVM guarantees several rules:
(1). If both A and B are of the same thread, then HB (A, B)
(2). If a is the unlock of the lock, and B is the lock on the same latch, then HB (A, B)
(3). If a is a write operation on a volatile variable, B is a read operation on the same variable, then HB (A, B)
...
...
(8). Transitivity: If HB (A, C) and HB (B, C), then HB (A, C)
Rule 1 is very obvious, the same thread, and the following actions are sure to see the previous action
Rule 2 shows that locks can be used to solve visibility problems
Rule 2 shows that volatile variables can also be used to solve visibility problems
Rule 8 shows that HB is transitive, in fact, HB is a partial-order relationship
Application of HB Law
Assuming there are now two threads, they perform the following actions:
Thread1 thread2---------------------------------------x = 1 (A) M.unlock (B) x = 2 (C) m.lock (D) y = x (E)
When e is executed, is e guaranteed to see C?
By Law 1,HB (d,e)
By Law 2,HB (b,d)
By law 1, HB (A, B)
Fully available, HB (A, E), but cannot be pushed out HB (C, E)
So, E is not necessarily able to see C, but E must be able to see a, so when executing E, it is possible to thread2 see the value of X or 1
Complete 8 Rules http://docs.oracle.com/javase/specs/jls/se5.0/html/memory.html#17.4.5
1, procedure Order rule, if a must occur before B, then happen before,
2, the law of the monitor, the unlocking of a monitor must occur in the subsequent lock on the same monitor
3, volatie variable rule: Write volatile variable must occur before subsequent read to it
4, Thread start law: Thread.Start must occur in the course of the action
5, thread termination rule: Any action in the thread must occur before the action in parentheses (the other thread detects that the thread has been terminated, returns successfully from the Thread.Join call, and Thread.isalive () returns false)
6, Interrupt rule: One thread calls another thread's interrupt must occur on another path to discover the interrupt.
7, the rule of termination: The end of an object's constructor must occur before the object's finalizer
8, transitivity: A occurs before B, B occurs before C, a must occur before C.
Understanding Happens-before