1

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.

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I wish you hadn't pointed me in the bottleneck direction. But you make sense. Thanks. I will accept in 7mins

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.