I have a static HashMap
that is initialized on server startup. Clients initialize their data from this map when they login.
Now I need to refresh this map, but
Lets assume that "refresh" means that you want to replace all entries in the hashmap with a fresh set loaded from (say) a file.
If the set of keys in the new mapping is a superset of the keys in the original mapping, AND if you application doesn't care if clients can set part of the old mapping and part of the new mapping at the same time, then you could use a ConcurrentHashMap
instead of a HashMap
, and replace the entries with a sequence of put
calls.
However, if keys are (or could be) different, or if the update needs to be atomic from the client's perspective then a ConcurrentHashMap
is not going to work. Instead, you need to declare map
as a volatile
and implement your refresh()
method as per your question.
As you point out, using synchronized
(or a single-writer-multiple-reader lock) is liable to lead to a concurrency bottleneck.
Note: using a volatile
is likely to give better performance than using a ConcurrentHashMap
even in the cases where the latter is a viable solution.