happens-before
Each action in a thread happens-before every action in that thread that comes later in the program's order.
An unlock (synchronized block or method exit) of a monitor happens-before every subsequent lock (synchronized block or method entry) of that same monitor.
A write to a volatile field happens-before every subsequent read of that same field.
A call to start on a thread happens-before any action in the started thread.
All actions in a thread happen-before any other thread successfully returns from a join on that thread.
如果一个操作执行的结果需要对另一个操作可见,那么这两个操作之间必须存在 happens-before 关系。
程序顺序规则:一个线程中的每个操作,happens- before 于该线程中的任意后续操作。
监视器锁规则:对一个监视器锁的解锁,happens- before 于随后对这个监视器锁的加锁。
volatile 变量规则:对一个 volatile 域的写,happens- before 于任意后续对这个 volatile 域的读。
传递性:如果 A happens- before B,且 B happens- before C,那么 A happens- before C。
注意,两个操作之间具有 happens-before 关系,并不意味着前一个操作必须要在后一个操作之前执行!happens-before 仅仅要求前一个操作(执行的结果)对后一个操作可见,且前一个操作按顺序排在第二个操作之前(the first is visible to and ordered before the second)。happens- before 的定义很微妙,后文会具体说明 happens-before 为什么要这么定义。
比如
int a = 1
int b = 2
int c=a
则根据happens-before规则,允许下面的执行顺序
int b = 2
或者
int b = 2
int a = 1
int c=a
或者
int a = 1
int b = 2
int c=a
总之, 仅需要保证后一个操作对前一个操作的结果有依赖,
保证前一个操作发生在后一个操作之前的相对顺序就行。
happens-before
保证前后有依赖关系的操作,具有相对执行顺序。
memory consistency
memory visibility
happens-before保证的了memory visibility , 避免了 memory consistency error
The key to avoiding memory consistency errors is understanding the happens-before relationship. This relationship is simply a guarantee that memory writes by one specific statement are visible to another specific statement.