问题描述
- 根据Java内存模型的要求,有人可以解释初始化安全性吗?
- 最终如何字段有助于实现初始化安全性?
- 构造函数在确保初始化安全性方面扮演什么角色?
- 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 behaviour for the fields that are declared as final
. First , all final
object fields are guarenteed 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);
}
}
访问<$的线程c $ c> list of 默认情况下,
的实例不会保证看到该列表中的10个元素。实际上,这个线程甚至可以看到 list
为 null
。但是,如果 list
被声明为 final
,那么,根据JMM的要求,列表
必须始终用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 it it.
其次,此初始化保证不限于 final
字段本身,但递归地扩展到它引用的所有对象。例如,如果上例中的列表
是列表
的列表本身,则保证外部线程将内部列表视为完全初始化。
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 list
s themselves , then the external thread is guaranteed to see the inner lists as fully initialized.
请注意,我们无处使用 synchronized
来实现内存中的这种安全性能见度(在关系之前发生)。
Note that nowhere are we using synchronized
to achieve this safety in memory visibility ( happens-before relationship).
这篇关于请解释Java内存模型中详述的初始化安全性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!