如果我想实现以下目标,我一直在使用 ConcurrentHashMap
。
- 能够在不抛出
ConcurrentModificationException
的情况下迭代 map ,而另一个线程正在修改 map 内容。 - 允许两个线程同时修改。
有时,我使用 enum
作为键,从 EnumMap Javadoc ,我意识到,
Iterators returned by the collection views are weakly consistent: they will never throw ConcurrentModificationException and they may or may not show the effects of any modifications to the map that occur while the iteration is in progress.
因此,更换对我来说安全吗
Map<Country, String> map = new ConcurrentHashMap<Country, String>();
与
Map<Country, String> map = Collections.synchronizedMap(new EnumMap<Country, String>(Country.class));
我知道 EnumMap
中没有 putIfAbsent
,但目前对我来说没问题,因为我不需要它。
最佳答案
你不能这样做有两个原因:
- 缺乏同步可能会导致内存可见性影响(因为
Collections.synchronizedMap
的迭代器不同步)。 Iterator
的契约(Contract)将被破坏 - 在hasNext()
之后调用next()
时,您可能会得到NoSuchElementException
> 返回true
。
关于java - 用 EnumMap 替换 ConcurrentHashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4703882/