gpt4 book ai didi

java - 读取对象的引用并读取 JMM 下对象的字段

转载 作者:行者123 更新时间:2023-11-30 02:23:26 27 4
gpt4 key购买 nike

这篇文章是在阅读后提出的:https://shipilev.net/blog/2016/close-encounters-of-jmm-kind/#pitfall-semi-sync

class Box {
int x;
public Box(int v) {
x = v;
}
}

class RacyBoxy {
Box box;

public synchronized void set(Box v) {
box = v;
}

public Box get() {
return box;
}
}

和测试:

@JCStressTest
@State
public class SynchronizedPublish {
RacyBoxy boxie = new RacyBoxy();

@Actor
void actor() {
boxie.set(new Box(42)); // set is synchronized
}

@Actor
void observer(IntResult1 r) {
Box t = boxie.get(); // get is not synchronized
if (t != null) {
r.r1 = t.x;
} else {
r.r1 = -1;
}
}
}

作者说有可能r.r1 == 0。我同意那。但是,我对解释感到困惑:

The actual failure comes from the fact that reading a reference to an object and reading the object’s fields are distinct under the memory model.

我同意

reading a reference to an object and reading the object’s fields are distinct under the memory model but, I don't see how it has an influence on result.

请帮我理解一下。

附注如果有人对 @Actor 感到困惑。它只是意味着:在线程中运行。

最佳答案

我认为它解决了阅读代码的人对顺序一致性的常见误解。对实例的引用在一个线程中可用这一事实并不意味着已设置其构造函数。换句话说:读取实例与读取实例字段是不同的操作。许多人认为一旦他们可以观察到一个实例,就需要运行构造函数,但由于缺少读取同步,上述示例并非如此。

关于java - 读取对象的引用并读取 JMM 下对象的字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46253422/

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