robinkc
robinkc

Reputation: 1348

Do we need to synchronize java HashMap gets if there is only one writer thread

I am maintaining an in-memory HashMap that stores list of testUserIds to their emailId.

HashMap<Integer, String> testUsers = new HashMap<>()

And there is just one background thread that reads additions/deletions to list of testUsers and performs the operations on this map. As there is only one thread writing to this map, I do not have to necessarily make it a synchronized map.

But there are multiple threads reading from this map. Do I need a ConcurrentHashMap if there is only one writer but multiple readers?

Upvotes: 4

Views: 961

Answers (2)

user320676
user320676

Reputation: 384

Yes, If you are working in a multi-threaded environment, then you have to consider synchronization otherwise unexpected data will be delivered.

Upvotes: 0

Eran
Eran

Reputation: 393936

Yes, you should use ConcurrentHashMap (or synchronize your Map externally). Otherwise, if the writer thread is modifying the Map while any of the other threads iterates over the Map, you could get a ConcurrentModificationException.

From HashMap's Javadoc :

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.

From ConcurrentModificationException's Javadoc :

java.util.ConcurrentModificationException

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future.

Upvotes: 6

Related Questions