gpt4 book ai didi

java - 有人可以澄清与完整初始化相关的 Java 内存模型最终字段语义吗?

转载 作者:太空宇宙 更新时间:2023-11-04 10:12:54 25 4
gpt4 key购买 nike

来自Java Memory Model specification :

An object is considered to be completely initialized when its constructor finishes. A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's final fields.

让我困惑的部分是这句话:

A thread that can only see a reference to an object after that object has been completely initialized is guaranteed to see the correctly initialized values for that object's final fields.

句子的主语是

A thread that can only see a reference to an object after that object has been completely initialized

该声明的其余部分仅适用于本主题。这对我来说意味着有些线程可以在对象完全初始化之前看到对该对象的引用。

如果存在此类线程,则本规范中与最终字段相关的保证仅适用于在某些情况

在旧的 Brian Goetz article from 2001 中,Goetz 描述了一个场景:

Suppose thread B comes along after the memory has been allocated and the resource field is set, but before the constructor is called. It sees that resource is not null, skips the synchronized block, and returns a reference to a partially constructed Resource!

这表明实际上存在一些线程可以在对象完全初始化之前看到对对象的引用。

Goetz 然后继续解释为什么使用 volatile 也无助于解决这个问题。

那么,如何保证在ObjectA完全初始化之前,某些Object B无法看到某些新的ObjectA呢?似乎只有在这些条件已经满足的情况下使用最终字段才有帮助。

最佳答案

This suggests to me that there are some threads that can see a reference to an object before that object has been completely initialized.

这是正确的。

如果构造函数或构造函数调用的某个方法将 this 发布到另一个线程可以看到它的某个位置,则可能会发生这种情况。 Goetz et al称其为“不安全的出版物”(IIRC。我的书在约 2 公里外的书架上。)

So, how do I guarantee that some Object B cannot see some new ObjectA before ObjectA is completely initialized?

ObjectA 构造函数不应将 this 发布到其他线程可以看到的地方。那么一切都很好1

<小时/>

1 - ....“全部”的一些定义。我们还要解决世界和平问题。

关于java - 有人可以澄清与完整初始化相关的 Java 内存模型最终字段语义吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52106517/

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