安全发布java.util.concurrent集合 [英] Safe publication of java.util.concurrent collections

查看:112
本文介绍了安全发布java.util.concurrent集合的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这段代码中的挥发性是多余的吗?

Is volatile redundant in this code?

public class Test {
    private volatile Map<String, String> map = null;

    public void resetMap() { map = new ConcurrentHashMap<>(); }

    public Map<String, String> getMap() { return map; }
}

换句话说, map = new ConcurrentHashMap ;>(); 提供任何可见性保证?

In other words, does map = new ConcurrentHashMap<>(); provide any visibility guarantees?

就我所见, http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/ConcurrentMap.html> ConcurrentMap 是:

As far as I can see, the only guarantee provided by ConcurrentMap is:


在将对象作为键或值放入ConcurrentMap之前,线程中的操作发生在访问或删除该对象之前的操作

Actions in a thread prior to placing an object into a ConcurrentMap as a key or value happen-before actions subsequent to the access or removal of that object from the ConcurrentMap in another thread.

如何使用java.util.concurrent(CopyOnWriteArrayList等)中的其他线程安全集合?

How about other thread safe collections in java.util.concurrent (CopyOnWriteArrayList, etc.)?

推荐答案

volatile 地图。即ConcurrentMap仅提供集合的内容,而不是引用集合的内容。

volatile is not redundant as you are changing the reference to the map. i.e. ConcurrentMap only provides guarentees about the contents of the collection, not references to it.

另一种方法是

public class Test {
    private final Map<String, String> map = new ConcurrentHashMap<>();

    public void resetMap() { map.clear(); }

    public Map<String, String> getMap() { return map; }
}




在java中其他线程安全集合.util.concurrent(CopyOnWriteArrayList等)?

How about other thread safe collections in java.util.concurrent (CopyOnWriteArrayList, etc.)?

只有集合的行为是线程安全的。对集合的引用不是线程安全的,集合中的元素不会通过将它们添加到集合中使线程安全。

Only the behaviour of the collection is thread safe. Reference to the collection are not thread safe, elements in the collection are not made thread safe by adding them to the collection.

这篇关于安全发布java.util.concurrent集合的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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