设置HashMap线程安全吗? [英] Is setting a HashMap thread safe?

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

问题描述

我的程序中有一个 HashMap ,它由多个线程访问,偶尔由一个线程设置。

I have a HashMap in my program which is accessed by multiple threads, and is occasionally set by a single thread.

例如:

Map<String, String> myMap = new HashMap<String, String>();

这是多个线程访问的。每小时一次,单个线程调用:

This is accessed by multiple threads. Once an hour, a single thread calls:

myMap = myRefreshedVersionOfTheMap;

所以我的问题是这是否是线程安全的。如果两个映射都始终具有键importantKey,那么读取线程是否可以在importantKey时访问映射不存在?

So my question is whether or not this is thread safe. If both maps always have the key "importantKey", is it possible for a reading thread to ever access the map at a time when "importantKey" does not exist?

编辑:

感谢答案,我已经意识到这个问题实际上与 HashMap 无关。这是一个关于对象引用赋值的问题。

Thanks to the answers, I've realized this question is actually independent of the HashMap. It was more a question about object reference assignment.

推荐答案

这不是线程安全的。即使在发布点之后没有写入地图本身(从执行发布的线程的角度来看),并且引用赋值是原子的,新的 Map<> 尚未安全发布。特别是, 在构造期间写入地图 - 无论是在构造函数中,还是之后,取决于您添加这些元素的方式,这些写入可能会被其他线程看到,也可能看不到,因为即使它们在地图发布到其他线程之前直观地发生,根据内存模型,这不是正式的情况。

This is not thread safe. Even though there are no writes to the map itself after the point of publication (from the point of view of the thread doing the publication), and reference assignment is atomic, the new Map<> has not been safely published. It particular, there are writes to the Map during its construction - either in the constructor, or after, depending on how you add those elements, and those writes may or may not be seen by other threads, since even though they intuitively occur before the map is published to the other threads, this isn't formally the case according to the memory model.

对于要安全发布的对象,必须使用某种机制将其传达给外部世界,该机制要么在对象构造,参考出版物和参考读​​取之间建立先前发生的关系,要么必须使用一些较窄的方法,保证发布安全:

For an object to be safely published, it must be communicated to the outside world using some mechanism that either establishes a happens-before relationship between the object construction, the reference publication and the reference read, or it must use a handful of narrower methods which are guaranteed to be safe for publishing:


  • 从静态初始值设定项初始化对象引用。

  • 将对它的引用存储到最终字段中。

如果你声明myMap volatile <你的习语是安全的/ code>。有关安全发布的更多详细信息,请参见 JCIP (强烈推荐),或此处,或者更长的回答

Your idiom would be safe if you declared myMap volatile. More details on safe publication can be found in JCIP (highly recommended), or here, or in this longer answer on a similar topic.

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

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