Question

I have a HashMap that I need multiple threads to access. My design is such that each thread will be reading and writing to its own entry in the map: the same map, but no two threads work on the same entry. No one thread will ever need to iterate over the map or call size(). So my question is: do I have to synchronize on the Hashmap or may I just use it with confidence that it will never throw a ConcurrentModificationException? My obvious worry is that synchronizing will create a huge bottleneck.

Was it helpful?

Solution

So my question is: do I have to synchronize on the Hashmap or may I just use it with confidence that it will never throw a ConcurrentModificationException?

You should use ConcurrentHashMap for this purpose. The issue is not just about iterating but it is also about memory synchronization.

... each thread will be reading and writing to its own entry in the map ...

This is someone ambiguous. If your HashMap is static in that the threads are only reading from the map and only making changes to the object that is referenced in the map but not changing the value in the map then you will be fine. You can initialize your map before the threads are started and they can use the map without memory synchronization.

However, if one thread changes the map in any manner to point to a new object, it must publish that change to central memory and other threads must see those updates. That requires memory synchronization on both the reading and writing sides.

My obvious worry is that synchronizing will create a huge bottleneck.

This smacks of premature optimization. Most likely you will be limit by IO long before contention over the map is an issue. In any case, switching to use a ConcurrentHashMap will alleviate your worries and it will be a minimal performance decrease compared to a non-synchronized map.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top