Egis
Egis

Reputation: 5141

Do you need to synchronized reading from HashMap?

I have a java.util.HashMap object. I guarantee that writing to HashMap is done by single dedicated thread. However, reading from the same HashMap object can be done from more that one thread at the time. Can I run in any troubles with such implementation?

Upvotes: 1

Views: 1097

Answers (1)

Stefan Ferstl
Stefan Ferstl

Reputation: 5265

Yes, you can run into big troubles with such an implementation!

Adding a value to the HashMap is not an atomic operation. So if you read the map from another thread you might see an inconsistent state when another thread is adding a value at the same time. This will lead to randomly unexpected behavior or exceptions when running your code. Furthermore, without synchronization it is not guaranteed when updated variables become visible to other threads.

So as 11thdimenstion said in the comment of your question you should really use ConcurrentHashMap for your purposes or properly synchronize your read and write access to the map.

Upvotes: 1

Related Questions