java - 如果线程不更改映射结构,我应该使用 ConcurrentHashMap 还是 HashMap?

标签 java concurrency hashmap concurrenthashmap

对于这种情况,我是否需要 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/

相关文章:

java - 如何让我的 ExpandableListView 等待加载,直到填充我的 HashMap?

java - java.util.HashMap 类的 keySet() 方法的时间复杂度是多少?

java - Android 库线程安全

java - 如何使用 Spring 实现自定义 WebSocket 子协议(protocol)

java - 如何在 ArrayList 上实现安全的读/写并发?

java - 每个线程都在单独的处理器上 - 这可能吗?

java - Bluestacks Android 模拟器是使用 .Net 构建的?

java - 将十六进制字符串转换为整数

java - Java中的并发和阻塞队列

java - 通用对象的哈希函数