gpt4 book ai didi

java - 对象创建(状态初始化)和线程安全

转载 作者:行者123 更新时间:2023-12-03 13:08:45 24 4
gpt4 key购买 nike

我正在查看“Java Concurrency in Practice”一书,发现下面引用的陈述真的很难相信(但不幸的是它是有道理的)。

http://www.informit.com/store/java-concurrency-in-practice-9780321349606

只是想弄清楚这 100%

public class Holder {
private int n;
public Holder(int n) { this.n = n; }
public void assertSanity() {
if (n != n)
throw new AssertionError("This statement is false.");
}
}

While it may seem that field values set in a constructor are the first values written to those fields and therefore that there are no "older" values to see as stale values, the Object constructor first writes the default values to all fields before subclass constructors run. It is therefore Possible to see the default value for a field as a stale value



关于上面的粗体声明,

我知道这种行为,但现在很明显,构造函数的这种调用层次结构不能保证是原子的(在由锁保护的单个同步块(synchronized block)中调用 super 构造函数),但是解决方案是什么?想象一个具有多个级别的类层次结构(即使不推荐,让我们假设它是可能的)。上面的代码片段是我们在大多数项目中每天都能看到的一种原型(prototype)。

最佳答案

你看错书了。它明确地说:

The problem here is not the Holder class itself, but that the Holder is not properly published.



所以上面的构造如果没问题。不好的是不正确地将这样的对象发布到其他线程。书中详细解释了这一点。

关于java - 对象创建(状态初始化)和线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46385877/

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