对象创建(状态初始化)和线程安全 [英] Object creation (state initialisation) and thread safety

查看:349
本文介绍了对象创建(状态初始化)和线程安全的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在研究实践中的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).

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

关于上面的粗体语句,

我知道行为现在很明显这个调用层次结构构造函数不保证是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:


这里的问题不是Holder类本身,而是Holder没有正确发布。

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

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

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.

这篇关于对象创建(状态初始化)和线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆