Search code examples
javamultithreadinghashmapconcurrenthashmap

Is it safe to use hashmap value reference when it may be updated in another thread


Is it safe to use getParameter

Since I can tolerate the value is not latest.
And when next time I can get the latest value of Parameter

Code like this :

 public class ParameterManager {

    private volatile Map<String, Parameter> scenarioParameterMap = Maps.newHashMap();

    public ParameterManager(String appName) throws DarwinClientException {
    }

    public Parameter getParameter(String scenario) {
        return scenarioParameterMap.get(scenario);
    }

    public void update(String scenario, Map<String, String> parameters) {
         if (scenarioParameterMap.containsKey(scenario)) {
             Parameter parameter = scenarioParameterMap.get(scenario);
             parameter.update(parameters);
         } else {
            scenarioParameterMap.put(scenario, new Parameter(scenario, parameters));
        }
    }
}

or the update is just use

             scenarioParameterMap.put(scenario, new Parameter(scenario, parameters));

Solution

  • volatile does not help here at all. It only protects the reference held in scenarioParameterMap, not the contents of that map. Since you're not reassigning it to point to a different map at any point, volatile is extraneous.

    This code is not threadsafe. You need to use proper synchronization, be that via synchronized, or using a concurrent map, or other equivalent method.

    Since I can tolerate the value is not latest.

    Thread non-safety can be more dangerous than that. It could give you wrong results. It could crash. You can't get by thinking that the worst case is stale data. That's not the case.

    Imagine that Map.put() is in the middle of updating the map and has the internal data in some temporarily invalid state. If Map.get() runs at the same time who knows what might go wrong. Sometimes adding an entry to a hash map will cause the whole thing to be reallocated and re-bucketed. Another thread reading the map at that time would be very confused.