问题描述
我有一个 java.util.HashMap
对象。我保证写入 HashMap
是由单个专用线程完成的。但是,从同一个 HashMap
对象读取数据可以同时从多个线程完成。这样的实现可以给我带来麻烦吗?
是的,这样的实现会给你带来很大的麻烦!
p>向HashMap添加值不是原子操作。因此,如果您从另一个线程读取映射,则当另一个线程同时添加值时,您可能会看到不一致的状态。运行代码时,这将导致随机的意外行为或异常。此外,如果没有同步,则不能保证更新后的变量对其他线程可见。 c> ConcurrentHashMap 用于您的目的,或正确同步您对地图的和读取权限。
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?
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.
这篇关于您需要同步从HashMap读取吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!