java哈希映射线程可见性 [英] java hash map thread visibility

查看:110
本文介绍了java哈希映射线程可见性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在初始化时完全加载了一个java HashMap,但在初始化之后,多个线程将从HashMap读取数据。我想避免任何类型的同步,因为地图基本上是只读的,永远不会改变。但我可以保证所有线程都可以看到所有键和值吗?

I am fully loading a java HashMap on initialization, but after initialization multiple threads will be reading the data from the HashMap. i'd like to avoid any type of synchronization since the map is essentially read only and never changes. But can i guarantee that all keys and values are visible to all threads?

推荐答案

如果地图的内容永远不会改变那么你就不要有问题。只有当变量的内容发生变化时,内存模型可见性问题才会发挥作用。

If the map's contents never change then you don't have a problem. Memory model visibility problems come into play only when the contents of a variable change.

您可能希望同步映射的初始化,以确保没有线程访问它在它完全初始化之前,并确保加载到地图中的值都是可见的。

You will likely want to synchronize the initialization of the map both to make sure no threads access it before it's fully initialized, and to make sure that the values loaded into the map are all visible.

编辑:最初我完全忽略了地图如何初始化的问题第一名。阅读其中一篇Pugh文章后(再次)似乎地图确实需要是最终的,以便初始化数据变得可见:

Originally I totally ignored the issue of how the map gets initialized in the first place. After reading one of the Pugh articles (again) it seems like the map really needs to be final in order for the initialization-data to become visible:


能够看到正确构造的字段值很好,但如果字段本身是引用,那么您还希望代码查看它指向的对象(或数组)的最新值。如果您的字段是最终字段,则也可以保证。因此,您可以拥有一个指向数组的最终指针,而不必担心其他线程看到数组引用的正确值,但是数组内容的值不正确。同样,在这里正确,我们的意思是对象的构造函数结束时的最新,而不是可用的最新值。

The ability to see the correctly constructed value for the field is nice, but if the field itself is a reference, then you also want your code to see the up to date values for the object (or array) to which it points. If your field is a final field, this is also guaranteed. So, you can have a final pointer to an array and not have to worry about other threads seeing the correct values for the array reference, but incorrect values for the contents of the array. Again, by "correct" here, we mean "up to date as of the end of the object's constructor", not "the latest value available".

有一个强制发生在之前关系的条件列表,在Java规范中给出,我应该在这里引用它们(或者,如果其他人在他们的答案中做了我会投票)。静态变量和Holder成语当然是一种方法。问题非常广泛,因为它没有指定地图如何初始化,如果你发布一个描述你如何建议进行初始化的问题,你可能会得到一个更直接有用的答案。

There is a list of conditions that force a 'happens-before' relationship, given in the Java spec, I should quote them here (or if somebody else does in their answer I will vote for it). The static variable and Holder idiom is certainly one way to go. The question is pretty broad as it doesn't specify how the map gets initialized, if you post a question describing how you propose to do the initialization you will likely get a more directly helpful answer.

这篇关于java哈希映射线程可见性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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