Do you need to synchronized reading from HashMap?

一曲冷凌霜 提交于 2020-08-10 08:44:11

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/33987181/do-you-need-to-synchronized-reading-from-hashmap

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!