Originally posted by Vijay Rathore:
[...]Do I need to synchronize this HashMap during update process as the clients are only reading the data?
Yes. During an update, the data structures inside the HashMap are updated - and may be updated quite drastically, as in an internal resize - and reading threads may be unable to access the data in the map. This is not necessarily confined to the key being updated. And even if in your particular use case it seems to work, do you want to be that tightly coupled to an implementation detail of HashMap in your particular JDK version?
The first question I'd ask is: have you shown that plain old synchronization is too costly? As in "profiler"? Remember that greater minds than yours or mine have found that
premature optimization is the root of all evil in programming.
A more academic point is that, looking at the JVM model, you do in general need synchronization for the memory barriers that guarantee that modifications to the HashMap are propagated to other threads. This is unlikely to be a consideration in practice though, if only because of all the synchronization that is going on in an application server anyway.
So the scenario is, only the thread is trying to update the HashMap after 30 minutes but all other clients are just reading the HashMap. What could be the highly optimized solution for this scenario?
Given that updates are infrequent, and that object reference r/w operations are atomic, one way to realize this scenario would be to never modify the Map (thereby allowing unsynchronized access) and update it by replacing the Map as a whole:
This approach also ensures that the update operation is fully atomic, which is an advantage if the various bits of data in the map have some consistency requirement.
Remember to take a
copy of the "data" reference every time you need it, so that (1) you minimize the number of volatile variable reads and (2) you ensure that the data you work with remains the same for the duration of your operation. In other words, don't do this
But do this
- Peter