我正在维护一个内存中的 HashMap
,它将 testUserIds
列表存储到他们的 emailId
。
HashMap<Integer, String> testUsers = new HashMap<>()
并且只有一个后台线程读取添加/删除到 testUsers
列表并在此映射上执行操作。由于只有一个线程写入此 map ,因此我不必将其设为同步 map 。
但是有多个线程正在读取这张 map 。如果只有一个作者但有多个读者,我是否需要 ConcurrentHashMap
?
最佳答案
是的,你应该使用 ConcurrentHashMap
(或在外部同步您的 Map
)。否则,如果编写器线程正在修改 Map
而任何其他线程遍历 Map
, 你可以得到一个 ConcurrentModificationException
.
来自 HashMap
的 Javadoc
:
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/