【发布时间】:2020-07-27 04:00:22
【问题描述】:
Java中存在两种最终记录规则,如下:
-
a write to final field in constructor和the constructed instance reference is assigned to variable afterwards无法重新排序 -
read a instance reference和read the final field in the instance afterwards无法重新排序
我们可以将上述规则视为发生之前的规则吗?
-
a write to final field in constructor发生在the constructed instance reference is assigned to variable afterwards -
read a instance reference发生之前read the final field in the instance afterwards
我认为happens-before规则语义更强。
【问题讨论】:
-
我认为“happens-before”较弱。 IIRC,“之前发生”仅表示线程内的“程序顺序”,加上由于同步而导致的一些线程间顺序。如果 A 发生在 B 之前,C 仍然可以观察到 B 已经发生但 A 尚未发生的不一致状态,如果 C 相对于 A 和 B 没有排序。
-
所以我认为关键不是“更强的语义”或“更弱的语义”,这只是推导吧?感谢您的回复。 @HTNW
标签: java final happens-before