这是对象的安全发布吗? [英] Is this a safe publication of object?

查看:101
本文介绍了这是对象的安全发布吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个课程项目

class Item {
  public int count;
  public Item(int count) {
    this.count = count;
  }
}

然后,我将在一个项目中引用一个项目其他类别的字段

Then, I will put a reference to Item in a field of other class

class Holder {
  public Item item;
  public Holder() {
    item = new Item(50);
  }
}

这个新物品对象安全发布?如果没有,为什么?根据Java Concurrency in Practice,新的Item发布而没有完全构造,但在我看来,新的Item是完全构造的:它的这个引用不会转义,并且它的引用及其状态会同时发布,因此使用者线程不会看到过时的值。或者是可见性问题。我不确切知道原因。

Can this new Item object be safely published? If not, why? According to Java Concurrency in Practice, the new Item is published without being fully constructed, but in my opinion the new Item is fully constructed: its this reference doesn't escape and the reference to it and its state is published at the same time, so the consumer thread will not see a stale value. Or is it the visibility problem. I don't exactly know the reason.

推荐答案


这个新的Item对象能否安全发布?如果没有,为什么?

Can this new Item object be safely published? If not, why?

该问题围绕指令的优化和重新排序。如果有两个线程使用构造对象而不进行同步,则可能会出现编译器决定为了效率而重新排序指令并为对象分配内存空间并将其引用存储在<$中的情况。 c $ c> item 字段之前完成构造函数和字段初始化。或者它可以重新排序内存同步,以便其他线程以这种方式感知

The issue revolves around optimizations and reordering of instructions. When you have two threads that are using a constructed object without synchronization, it may happen that the compiler decides to reorder instructions for efficiency sake and allocate the memory space for an object and store its reference in the item field before it finishes with the constructor and the field initialization. Or it can reorder the memory synchronization so that other threads perceive it that way.

如果你标记字段为 final 然后构造函数保证完成该字段的初始化作为构造函数的一部分。否则,在使用锁之前,您必须同步锁定。这是 Java语言定义的一部分

If you mark the item field as final then the constructor is guaranteed to finish initialization of that field as part of the constructor. Otherwise you will have to synchronize on a lock before using it. This is part of the Java language definition.

这是另外几个参考:

  • Double check locking is broken
  • Synchronization and the Java Memory Model

这篇关于这是对象的安全发布吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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