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
volatilekeyword does. It makes sure that if the reference value held by the variable declaredvolatilechanges, other threads will see it rather than having a cached copy. It has nothing to do with thread-safety in regard to accessing theHashMapGiven that, and the fact that you say the
HashMapis read-only … you certainly don’t need to use anything that provides thread-safety including aConcurrentHashMapEdit 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
HashMapthen assigning it to the existing variable, then you usevolatile