如果只有一个编写器线程,是否需要同步java HashMap获取
我正在维护一个内存中的HashMap
,它将testUserIds
列表存储到它们的emailId
HashMap<Integer, String> testUsers = new HashMap<>()
只有一个后台线程读取testUsers
列表的添加/删除,并在此映射上执行操作。由于只有一个线程写入此映射,因此我不必将其设置为同步映射
但有多个线程正在读取此地图。如果只有一个writer但有多个reader,我是否需要一个ConcurrentHashMap
# 1 楼答案
是的,如果您在多线程环境中工作,那么您必须考虑同步,否则将传递意外数据。p>
# 2 楼答案
是的,您应该使用
ConcurrentHashMap
(或者从外部同步您的Map
)。否则,如果编写器线程正在修改Map
,而其他任何线程都在Map
上迭代,则可能会得到ConcurrentModificationException
从
HashMap
的Javadoc
开始:从
ConcurrentModificationException
的Javadoc: