java - 如果只有一个编写器线程,我们是否需要同步 java HashMap gets

标签 java hashmap synchronization

我正在维护一个内存中的 HashMap,它将 testUserIds 列表存储到他们的 emailId

HashMap<Integer, String> testUsers = new HashMap<>()

并且只有一个后台线程读取添加/删除到 testUsers 列表并在此映射上执行操作。由于只有一个线程写入此 map ,因此我不必将其设为同步 map 。

但是有多个线程正在读取这张 map 。如果只有一个作者但有多个读者,我是否需要 ConcurrentHashMap

最佳答案

是的,你应该使用 ConcurrentHashMap (或在外部同步您的 Map)。否则,如果编写器线程正在修改 Map而任何其他线程遍历 Map , 你可以得到一个 ConcurrentModificationException .

来自 HashMapJavadoc :

Note that this implementation is not synchronized. If multiple threads access a hash map concurrently, and at least one of the threads modifies the map structurally, it must be synchronized externally.

来自 ConcurrentModificationException的 Javadoc:

java.util.ConcurrentModificationException

This exception may be thrown by methods that have detected concurrent modification of an object when such modification is not permissible.

For example, it is not generally permissible for one thread to modify a Collection while another thread is iterating over it. In general, the results of the iteration are undefined under these circumstances. Some Iterator implementations (including those of all the general purpose collection implementations provided by the JRE) may choose to throw this exception if this behavior is detected. Iterators that do this are known as fail-fast iterators, as they fail quickly and cleanly, rather that risking arbitrary, non-deterministic behavior at an undetermined time in the future.

关于java - 如果只有一个编写器线程,我们是否需要同步 java HashMap gets,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40633960/

相关文章:

algorithm - 节点 s 的子树中值为 x 的节点数?

java - 理解 HashMap 中 equals 和 hashCode 的工作原理

c - 如果我在下面的代码片段中跳过 waiting[i] = false 会发生什么?

java - 同步异步后端

java - 获取帐户 android 的身份验证 token 时显示对话框

java - 将任务添加到执行器

java - 无法获得要编译的代码,有什么想法吗?

java - Ruby 相当于 64 位的 Calendar.getInstance().getTimeInMillis()

java - HashMap put() api 时间复杂度

javascript - 同步滚动 3(+) 个元素?