gpt4 book ai didi

java - 用 EnumMap 替换 ConcurrentHashMap

转载 作者:搜寻专家 更新时间:2023-10-31 19:49:57 24 4
gpt4 key购买 nike

如果我想实现以下目标,我一直在使用 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com