Search code examples
javamultithreadinghashmapconcurrenthashmap

Ensure all threads updating a single entry in a map in Java


I have a method that is called by multiple threads at the same time. Within it, I am trying to handle a scenario as explained by the snippet below:

Map<Object,Long> syncMap = Collections.synchronizedMap(normalHashMap);

Runnable mapOperations = () -> {
    synchronized (syncMap) {
        if (MapUtils.isNotEmpty(syncMap))
        {
            Object currentCount = syncMap.get(entryKey);

            // Every thread should execute this once. Every thread brings a value and that gets added up and stored for this "key"
            syncMap.put(key, value + valueFromThisThread);
        }
    }
};
mapOperations.run();

Every thread should execute the block above once. Every thread brings a long value and that gets added up and stored for this one "key" entry in the map.

Can someone please confirm if this would work?


Solution

  • Your code should work fine. Additionally, if you want to make sure you don't cache the field in the CPU cache, you might want to define it as a volatile, like:

    volatile Map<Object,Long> syncMap = Collections.synchronizedMap(normalHashMap);
    

    Also, you don't need a synchronized { } block if you use the SynchronizedMap.