从多个线程获取java.util.HashMap的值是否安全?(没有修改)? [英] Is it safe to get values from a java.util.HashMap from multiple threads (no modification)?

查看:141
本文介绍了从多个线程获取java.util.HashMap的值是否安全?(没有修改)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有一种情况会创建一个地图,一旦初始化,就不会再被修改。然而,它将被访问(通过get(key))从多个线程。这样可以安全地使用 java.util.HashMap 吗?

There is a case where a map will be constructed, and once it is initialized, it will never be modified again. It will however, be accessed (via get(key) only) from multiple threads. Is it safe to use a java.util.HashMap in this way?

使用 java.util.concurrent.ConcurrentHashMap ,并没有测量需要提高性能,但只是好奇如果一个简单的 HashMap 就足够了,因此,这个问题不是我应该使用哪一个?也不是一个性能问题,而是问题是它会安全吗? >

(Currently, I'm happily using a java.util.concurrent.ConcurrentHashMap, and have no measured need to improve performance, but am simply curious if a simple HashMap would suffice. Hence, this question is not "Which one should I use?" nor is it a performance question. Rather, the question is "Would it be safe?")

推荐答案

Jeremy Manson,当谈到Java内存模型时,有一个关于这个主题的三部分博客 - 因为实质上询问访问不可变HashMap是否安全的问题,答案是肯定的。但是你必须回答这个问题的谓词 - 我的HashMap是不可变的。

Jeremy Manson, the god when it comes to the Java Memory Model, has a three part blog on this topic - because in essence you are asking the question "Is it safe to access an immutable HashMap" - the answer to that is yes. But you must answer the predicate to that question which is - "Is my HashMap immutable". The answer might surprise you - Java has a relatively complicated set of rules to determine immutability.

有关这个主题的更多信息,请阅读Jeremy的博客文章:

For more info on the topic, read Jeremy's blog posts:

关于Java不变性的第1部分:
http://jeremymanson.blogspot.com/2008/04/immutability-in-java.html

Part 1 on Immutability in Java: http://jeremymanson.blogspot.com/2008/04/immutability-in-java.html

第2部分的不变性Java:
http:// jeremymanson。 blogspot.com/2008/07/immutability-in-java-part-2.html

Part 2 on Immutability in Java: http://jeremymanson.blogspot.com/2008/07/immutability-in-java-part-2.html

第3部分关于Java中的不可变性:
< a href =http://jeremymanson.blogspot.com/2008/07/immutability-in-java-part-3.html =nofollow noreferrer> http://jeremymanson.blogspot.com/2008/07 /immutability-in-java-part-3.html

Part 3 on Immutability in Java: http://jeremymanson.blogspot.com/2008/07/immutability-in-java-part-3.html

这篇关于从多个线程获取java.util.HashMap的值是否安全?(没有修改)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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