问题
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