Java并发 - 发布不可变对象(Java Concurreny In Practice) [英] Java Concurrency - Publishing Immutable Objects (Java Concurreny In Practice)

查看:187
本文介绍了Java并发 - 发布不可变对象(Java Concurreny In Practice)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在Java并发在实践中,作者指出

In Java Concurrency In Practice, the author stated that


  1. 不可变对象可以通过任何机制发布

  2. 不可变对象可以被任何线程安全地使用,无需额外的同步,即使不使用同步来发布它们。

是否意味着以下成语对于发布不可变对象是安全的?

Does it mean that the following idioms are safe to publish immutable objects?

public static List<ImmutableObject> list = new ArrayList<ImmutableObject>();

// thread A invokes this method first
public static void methodA () {
    list.add(new ImmutableObject());
}

// thread B invokes this method later
public static ImmutableObject methodB () {
    return list.get(0);
}

会有数据竞赛吗?
(这意味着线程B可能无法看到线程A添加的列表中的不可变对象)

Would there be any data race? (which means thread B may not be able to see the Immutable Object in the list added by thread A)

非常感谢。

更多,作者说如果Resource是不可变的,下面的代码是安全的。

More, the author said that the following code is safe if Resource is immutable.

@NotThreadSafe
public class UnsafeLazyInitialization {
    private static Resource resource;

    public static Resource getInstance() {
        if (resource == null)
            resource = new Resource();  // unsafe publication
        return resource;
    }
}




.3
初始化安全性的保证允许正确构造的不可变对象在不同步的情况下安全共享,无论它们如何发布,即使使用数据竞争发布也是如此。 (这意味着 unsafeLazyInitialization 实际上是安全的,如果 Resource 是不可变的。)

Section16.3 The guarantee of initialization safety allows properly constructed immutable objects to be safely shared across threads without synchronization, regardless of how they are published even if published using a data race. (This means that unsafeLazyInitialization is actually safe if Resource is immutable.)

对于这个问题的第二部分,将在另一个问题中详细讨论(点击这里

推荐答案

是的,你是对的,有数据竞赛。

Yes, you are correct, there is a data race.

只有 ImmutableObject 是不可变的,安全地在线程之间,你的 List ,但是,没有这些相同的保证,所以在添加 ImmutableObject 并检索它。

Only the ImmutableObject is immutable and can be shared safely between threads, your List, however, does not have these same guarantees, so there is a data race between adding the ImmutableObject and retrieving it.

在JCIP中,作者的意思是,不可变的对象是安全的发布,因为你不必担心做防御

In JCIP, the authors meant immutable objects are safe to publish in the sense that you don't have to worry about doing things like making defensive copies.

至于:


不可变对象可以安全地使用线程没有额外的
同步,即使不使用同步来发布

Immutable objects can be used safely by any thread without additional synchronization, even when synchronization is not used to publish them.

给定2个线程的一个不可变对象 A ,他们都通过任何方式获得,他们都可以使用对象 A 关于线程安全问题。

This statement means that given 2 threads with an immutable object A that they both acquired through any means, they can both use object A without worrying about thread-safety issues.

这篇关于Java并发 - 发布不可变对象(Java Concurreny In Practice)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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