java哈希映射线程可见性

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

解决方法

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

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

编辑:本来我完全忽略了地图如何初始化的问题.阅读one of the Pugh articles(再次)似乎地图真的需要是最终的,以便初始化数据变得可见:

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规范中给出,我应该在这里引用它(或者如果有人在他的答案中我会投票).静态变量和持有者成语当然是一种方式.问题是相当广泛的,因为它没有指定地图如何初始化,如果你发布一个问题描述你如何提出初始化,你可能会得到一个更直接有用的答案.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...