开发者社区 问答 正文

[@古散][¥20]JMM 中,Happens-Before 与 指令排序

int a = 1;
int b = 1;

这里,第一行与第二行代码是否有 Happens-Before 关系?

因为这两行代码的相关指令是可以重排的。

如果其有 Happens-Before 关系,是否意味着 Happens-Before 关系并不一定必须保障?

如果它们没有 Happens-Before 关系,如何理解下面句子?

If we have two actions x and y, we write hb(x, y) to indicate that x happens-before y.

  • If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).

上述引用来自于 Java Doc

展开
收起
风雪乐雨 2018-11-01 09:51:47 2700 分享 版权
1 条回答
写回答
取消 提交回答
  • 1.阿里云大学荣誉讲师, 2.MongoDB中文社区专家

    1.例子中的2行代码之间没有依赖关系,也就是说重排不会影响结果,在并发多线程模式下编译器或者CPU可能会重排。
    2.Happens-Before规则提供了参考性原则,为了保证操作之间的顺序性。例子中的代码,可以认为受此原则监管,但是没有触发规则。
    就好比每个人开车都准守交通法规,但是目前开车的人并没有违反规则,不触发处罚机制。
    3.Happens-Before属于JSR-133内存模型提供的潜规则,不论用不用底层都存在,只是某些情况例外,因为不影响执行结果。
    If we have two actions x and y, we write hb(x, y) to indicate that x happens-before y.

    If x and y are actions of the same thread and x comes before y in program order, then hb(x, y).
    这两句话的本义是方便我们理解Happens-Before规则:
    如果2个操作X和Y,我们说hb(x, y) ,表示X操作在Y操作之前发生。
    如果X和Y操作在同一个线程中,X在Y之前可以确定为hb(x, y)。

    2019-07-17 23:11:40
    赞同 展开评论
问答分类:
问答地址: