Volatile HashMap和ConcurrentHashMap [英] Volatile HashMap vs ConcurrentHashMap
问题描述
我有一个缓存类,它包含一个 volatile HashMap< T>
来存储缓存项。
好奇将 volatile HashMap
更改为 ConcurrentHashMap
?的结果会是什么?
我会提高性能吗?这个缓存是只读缓存。
什么是最好的选择?只是HashMap?
首先,看起来你不明白是什么, volatile
关键字。它确保如果由声明为 volatile
的变量保存的引用值发生变化,其他线程将看到它,而不是具有高速缓存的副本。它与访问 HashMap
无关的线程安全无关。你说的 HashMap
是只读...你肯定不需要使用任何提供线程安全包括 ConcurrentHashMap
要添加的:您最近一次编辑的内容为缓存正在填充一段时间
这不是只读的,是吗?
如果你要读取线程, (更新现有的HashMap),那么您应该使用 ConcurrentHashMap
,是的。
如果您填充一个全新的 HashMap
,然后将其分配给现有变量,则使用 volatile
I have a cache class which contains a volatile HashMap<T>
to store cache items.
I'm curious what would be the consequences of changing volatile HashMap
to ConcurrentHashMap
?
Would i gain performance increase? This cache is readonly cache.
What would be the best option to use? just HashMap? Cache is being populated on a interval.
First, it appears you don't understand what the volatile
keyword does. It makes sure that if the reference value held by the variable declared volatile
changes, other threads will see it rather than having a cached copy. It has nothing to do with thread-safety in regard to accessing the HashMap
Given that, and the fact that you say the HashMap
is read-only ... you certainly don't need to use anything that provides thread-safety including a ConcurrentHashMap
Edit to add: Your last edit you now say "The cache is being populated on a interval"
That's not read-only then, is it?
If you're going to have threads reading from it while you are writing (updating the existing HashMap) then you should use a ConcurrentHashMap
, yes.
If you are populating an entirely new HashMap
then assigning it to the existing variable, then you use volatile
这篇关于Volatile HashMap和ConcurrentHashMap的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!