gpt4 book ai didi

java - happens-before规则与初始化安全规则的关系

转载 作者:行者123 更新时间:2023-12-04 15:39:42 24 4
gpt4 key购买 nike

我正在阅读 Java Concurrency in Practice书。

在阅读关于 JMM 的章节时,它说:

The JMM defines a partial ordering called happens-before on all actions within the program. To guarantee that the thread executing action B can see the results of action A (whether or not A and B occur in different threads), there must be a happens-before relationship between A and B.

但是,我不能使用任何先行规则来推导“初始化安全”规则:

Initialization safety guarantees that for properly constructed objects, all threads will see the correct values of final fields that were set by the constructor, regardless of how the object is published.

我们可以使用 happens-before 规则来推导出“初始化安全”规则,还是这两个概念只是同一层次的抽象?

最佳答案

“初始化安全规则”是一种特殊的规则,不能从其他happens-before 关系派生,也不能与其他happens-before 关系相结合导出更多规则。

规则在JLS §17.5, final Field Semantics中指定:

final fields also allow programmers to implement thread-safe immutable objects without synchronization. A thread-safe immutable object is seen as immutable by all threads, even if a data race is used to pass references to the immutable object between threads. This can provide safety guarantees against misuse of an immutable class by incorrect or malicious code. final fields must be used correctly to provide a guarantee of immutability.

章节太长无法完整引用,但我想强调一下this specific statement :

This happens-before ordering does not transitively close with other happens-before orderings.

因此,除了其他先发生关系之外,还存在“初始化安全规则”,以帮助构建不可变对象(immutable对象)。

关于java - happens-before规则与初始化安全规则的关系,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58250258/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com