问题描述
我正在研究实践中的Java并发一书,发现在下面引用的陈述中很难相信(但遗憾的是它有意义)。
I am look into the book "Java Concurrency in Practice" and found really hard to believe below quoted statement (But unfortunately it make sense).
只想了解这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.");
}
}
关于上面的粗体语句,
我知道行为现在很明显这个调用层次结构构造函数不保证是ATOMIC(在锁定保护的单个同步块中调用超级构造函数),但是解决方案是什么?想象一个具有多个级别的类层次结构(即使不推荐,也可以假设它是可能的)。上面的代码片段是我们在大多数项目中每天看到的一种原型。
I am aware that the behaviour BUT now it is clear that this calling hierarchy of constructors is NOT guarantee to be ATOMIC (calling super constructors in single synchronised block that is guarded by a lock), but what would be the solution? imagine a class hierarchy that has more than one level (even it is not recommended, lets assume as it is possible). The above code snippest is a kind of a prototype that we see everyday in most of the projects.
推荐答案
你误读了这本书。它明确地说:
You misread the book. It explicitely says:
所以上面的构造如果罚款。什么不好是将这样的对象不正确地发布到其他线程。这本书详细解释了这一点。
So the above construct if fine. What's not fine is to improperly publish such an object to other threads. The book explains that in details.
这篇关于对象创建(状态初始化)和线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!