你应该使用ConcurrentHashMap还是HashMap,如果线程不会更改映射的结构?

huangapple go评论68阅读模式
英文:

Should I use ConcurrentHashMap or HashMap if I threads don't change structure of map?

问题

在这种情况下,我需要在Java中使用ConcurrentHashMap吗?

在将HashMap传递给一堆线程之前,我使用所有必要的键来初始化该映射:

Key = "thread1Key", Value = null
Key = "thread2Key", Value = null
Key = "thread3Key", Value = null
...

每个任务都是Runnable的一部分(由线程执行),并被分配为仅更改其中1个键的值。它是预分配的。换句话说,我不需要担心多个Runnable可能会更改哈希映射中的相同键的情况。

在这种情况下,是否需要ConcurrentHashMap,还是普通的HashMap就足够了?为什么?

谢谢!

英文:

Do I need a ConcurrentHashMap in Java for this case:

Before, passing the HashMap to a bunch of threads, I initiate the map with all the keys necessary:

Key = "thread1Key", Value = null
Key = "thread2Key", Value = null
Key = "thread3Key", Value = null
...

Each task is part of a Runnable (executed by a thread) and is assigned to alter the value of ONLY 1 of those keys. It's preassigned. In other words, I don't need to worry about the case where multiple Runnables may alter the same key in the hashmap.

In this case is ConcurrentHashMap required or a regular HashMap would do? And why?

Thanks!

答案1

得分: 4

这个对于 HashMap 的使用在没有额外同步的情况下是安全的。文档 正好描述了你的使用情况:

如果多个线程同时访问哈希映射,并且至少有一个线程对映射进行了结构性修改,那么必须在外部进行同步。(结构性修改是指添加或删除一个或多个映射的任何操作;仅仅更改实例已包含的键的关联值不是结构性修改。)

英文:

This usage of HashMap is safe without additional synchronization. The docs describe exactly your use case:

> If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally. (A structural modification is any operation that adds or deletes one or more mappings; merely changing the value associated with a key that an instance already contains is not a structural modification.)

答案2

得分: 3

一个 HashMap 在这种情况下可能在结构上保持一致,但还存在其值的可见性问题。如果一个线程中的值被更改,那么不能保证其他线程会看到它。或者如果其他线程看到了它,那么它也可能不一致,因为它没有在线程之间安全地发布。

英文:

A HashMap may stay structurally consistent in such a scenario, but there's also the issue of the visibility of its values. If a value is changed in one thread, then it is not guaranteed to be seen by the other threads. Or if it is, then it could also be inconsistent as it's not safely published between the threads.

答案3

得分: 0

一个常规的地图足够了,如果地图中没有删除条目。

英文:

A regular map is sufficient if there are no removal of entries in map.

huangapple
  • 本文由 发表于 2020年8月9日 02:05:48
  • 转载请务必保留本文链接:https://go.coder-hub.com/63318714.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定