对于这种情况,我是否需要 Java 中的 ConcurrentHashMap:
在将 HashMap 传递给一堆线程之前,我使用所有必要的键启动映射:
Key = "thread1Key", Value = null
Key = "thread2Key", Value = null
Key = "thread3Key", Value = null
...
每个任务都是 Runnable 的一部分(由线程执行),并被分配以更改这些键中只有 1 个的值。它是预先分配的。换句话说,我不需要担心多个 Runnable 可能会更改 hashmap 中的相同键的情况。
在这种情况下,需要 ConcurrentHashMap 还是常规的 HashMap?为什么?
谢谢!
最佳答案
HashMap
的这种用法在没有额外同步的情况下是安全的。 docs准确描述您的用例:
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.)
关于java - 如果线程不更改映射结构,我应该使用 ConcurrentHashMap 还是 HashMap?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63318714/