gpt4 book ai didi

java - Java 内存模型中的部分构造对象

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:39:26 26 4
gpt4 key购买 nike

我遇到了以下代码 in an article somewhere on the Internet :

public class MyInt {

private int x;

public MyInt(int y) {
this.x = y;
}

public int getValue() {
return this.x;
}
}

文章指出

Constructors are not treated special by the compiler (JIT, CPU etc) so it is allowed to reorder instructions from the constructor and instructions that come after the constructor.

此外,this JSR-133 article关于 Java 内存模型的声明

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.

上面提到的 MyInt 实例似乎是不可变的(除非该类未标记为 final)并且是线程安全的,但文章声明它不是。他们声明不能保证 x 在读取时始终具有正确的值。

但我认为

only the thread that creates an object should have access to it while it is being constructed

Java Tutorials似乎很支持。

我的问题是:这是否意味着,对于当前的 JMM,由于指令重新排序,线程可以访问部分构造的对象?如果是,怎么办?这是否意味着 Java 教程中的陈述根本不正确?

最佳答案

那篇文章说如果你有这样的代码

foo = new MyInt(7);

在一个有字段的类中

MyInt foo;

那么指令就是

(reference to new object).x = 7;
foo = (reference to new object);

可以作为某种优化进行交换。这永远不会改变运行此代码的线程的行为,但其他线程可能会在该行之后读取 foo

foo = (reference to new object);

但是在行之前

(reference to new object).x = 7;

在这种情况下,它会将 foo.x 视为 0,而不是 7。也就是说,其他线程可以运行

int bar = someObject.getFoo().getValue();

并以 bar 等于 0 结束。

我从未在野外见过这样的事情,但作者似乎知道他在说什么。

关于java - Java 内存模型中的部分构造对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45857765/

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