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

问题描述

在Java Concurrency in Practice中,作者指出

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;
    }
}

对于此问题的第二部分,将在另一个问题中进行详细讨论(单击此处)

推荐答案

是的,您是正确的,存在数据争用.

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.

关于:

此语句意味着给定两个线程都具有通过任何方式获取的不变对象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并发实践)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 18:12