Please explain initialization safety as spelled out in Java memory model(请解释 Java 内存模型中说明的初始化安全性)
问题描述
- 有人可以按照 Java 内存模型的要求解释 初始化安全 吗?
- final 字段如何帮助实现初始化安全?
- 构造函数在确保初始化安全方面扮演什么角色?
- Can some one explain initialization safety as required by Java memory model ?
- How does the final fields help in achieving initialization safety ?
- What role does the constructor play in ensuring initialization safety ?
推荐答案
初始化安全性提供了一个外部线程在其完全构造(初始化)状态下可以看到的对象.前提是对象不应过早发布,即.在它的构造函数中.一旦确保了这一点,JMM 就要求声明为 final
的字段具有某些行为.首先,所有 final
对象字段都保证在完全初始化的状态下被外部线程看到.这并不像听起来那么简单.
Initialization safety provides for an object to be seen by an external thread in its fully constructed (initialized) state. The prerequisite is that the object should not be published prematurely ie. in its constructor. Once this is ensured, JMM requires certain behavior for the fields that are declared as final
. First, all final
object fields are guaranteed to be seen by an external thread in its fully initialized state. This is not as trivial as it sounds.
考虑一个类:
class A {
List list;
A() {
list = Arrays.asList(some init expressions that adds 10 elements to list);
}
}
默认情况下,访问 A's
实例的 list
的线程不能保证在该列表中看到 10 个元素.事实上,这个线程甚至可以将 list
视为 null
.然而,如果 list
被声明为 final
,那么,根据 JMM 的要求,list
必须始终显示为已初始化,其中包含 10 个元素.
A thread that accesses the list
of A's
instance is not by default guaranteed to see 10 elements in that list. In fact, this thread can even see list
as null
. However, if list
is declared final
, then, as required by JMM, the list
must always appear to be initialized with 10 elements in it.
其次,这种初始化保证不限于 final
字段本身,而是递归地扩展到它所引用的所有对象.例如,如果上面示例中的 list
是列表本身的列表,则外部线程可以保证将内部列表视为完全初始化.
Secondly, this initialization guarantee is not limited to the final
field itself but is extended recursively to all objects referred by it. For example, if the list
in the above example is a list of lists themselves, then the external thread is guaranteed to see the inner lists as fully initialized.
请注意,我们在任何地方都没有使用 synchronized
来实现这种内存可见性的安全性(happens-before 关系).
Note that nowhere are we using synchronized
to achieve this safety in memory visibility (happens-before relationship).
这篇关于请解释 Java 内存模型中说明的初始化安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:请解释 Java 内存模型中说明的初始化安全性
基础教程推荐
- 如何在不安装整个 WTP 包的情况下将 Tomcat 8 添加到 Eclipse Kepler 2022-01-01
- Java 中保存最后 N 个元素的大小受限队列 2022-01-01
- 首次使用 Hadoop,MapReduce Job 不运行 Reduce Phase 2022-01-01
- 由于对所需库 rt.jar 的限制,对类的访问限制? 2022-01-01
- Spring Boot Freemarker从2.2.0升级失败 2022-01-01
- 在螺旋中写一个字符串 2022-01-01
- 如何使用 Stream 在集合中拆分奇数和偶数以及两者的总和 2022-01-01
- 如何使用 Eclipse 检查调试符号状态? 2022-01-01
- 如何强制对超级方法进行多态调用? 2022-01-01
- 如何对 HashSet 进行排序? 2022-01-01