请解释 Java 内存模型中说明的初始化安全性

  1. 有人可以按照 Java 内存模型的要求解释 初始化安全 吗?
  2. final 字段如何帮助实现初始化安全?
  3. 构造函数在确保初始化安全方面扮演什么角色?
  1. Can some one explain initialization safety as required by Java memory model ?
  2. How does the final fields help in achieving initialization safety ?
  3. 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).

相关文章