内存一致性

jdk内存一致性

内存一致性

java-memory-model-1 内存模型

happens-before

  1. Each action in a thread happens-before every action in that thread that comes later in the program's order.

  2. An unlock (synchronized block or method exit) of a monitor happens-before every subsequent lock (synchronized block or method entry) of that same monitor.

  3. A write to a volatile field happens-before every subsequent read of that same field.

  4. A call to start on a thread happens-before any action in the started thread.

  5. 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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值