happens-before规则与初始化安全规则的关系
Relationship between happens-before rules and initialization safety rule
我正在阅读 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" 规则:
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 规则来推导 "Initialization safety" 规则,还是这两个概念只是同一层次的抽象?
“初始化安全规则”是一个特殊的规则,不能从其他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.
因此,除了其他 happens-before 关系之外,还存在“初始化安全规则”,以帮助构建不可变对象。
我正在阅读 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" 规则:
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 规则来推导 "Initialization safety" 规则,还是这两个概念只是同一层次的抽象?
“初始化安全规则”是一个特殊的规则,不能从其他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.
因此,除了其他 happens-before 关系之外,还存在“初始化安全规则”,以帮助构建不可变对象。