java - 用 EnumMap 替换 ConcurrentHashMap

标签 java

如果我想实现以下目标,我一直在使用 ConcurrentHashMap

  1. 能够在不抛出 ConcurrentModificationException 的情况下迭代 map ,而另一个线程正在修改 map 内容。
  2. 允许两个线程同时修改。

有时,我使用 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,但目前对我来说没问题,因为我不需要它。

最佳答案

你不能这样做有两个原因:

  1. 缺乏同步可能会导致内存可见性影响(因为 Collections.synchronizedMap 的迭代器不同步)。
  2. Iterator 的契约(Contract)将被破坏 - 在 hasNext() 之后调用 next() 时,您可能会得到 NoSuchElementException > 返回 true

关于java - 用 EnumMap 替换 ConcurrentHashMap,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4703882/

相关文章:

java - 向 Eclipse 添加 Windows 命令行提示右键单击选项

java - System.nanoTime 的准确度应该如何? - java

java SimpleDateFormat.parse 将 UTC 时间转换为亚洲/香港时间

java - Spring 3.1.0 mvc 绑定(bind) modelattribute 以及 requestbody

java - 鉴别器公式

java - 从网页中获取所有超链接并在java中递归地执行此操作

java - 映射 google 自定义搜索 api URL 中的文本框值

java - 将图像设置为 JFrame 的背景

java - 覆盖公历中的 tostring 方法

java - 如何使用 groovy 将另一个 xml 文件内容添加到现有 xml 创建中