对本例中 ConcurrentHashMap 和 HashMap 行为的区别感到困惑

Confused on the difference between ConcurrentHashMap and HashMap behavior in this example

我正在尝试了解 ConcurrentHashMap 的工作原理。我找到了一个例子,但我无法理解。这是它的代码:

Map<String, Object> myData = new HashMap<String, Object>();
myData.put("A", 1);
myData.put("B", 2);
for (String key : myData.keySet()) {
    myData.remove(key);
}

这将在运行时抛出异常ConcurrentModificationException

但是,使用 ConcurrentHashMap 的代码可以正常工作:

Map<String, Object> myData = new ConcurrentHashMap<String, Object>();
myData.put("A", 1);
myData.put("B", 2);
for (String key : myData.keySet()) }
    myData.remove(key);
}

有人可以向我解释为什么 ConcurrentHashMap 允许删除键而 HashMap 抛出异常吗?谢谢

这只是 ConcurrentHashMap 的功能之一。引用文档:

Similarly, Iterators, Spliterators and Enumerations return elements reflecting the state of the hash table at some point at or since the creation of the iterator/enumeration. They do not throw ConcurrentModificationException.

然而,

ConcurrentHashMap 并没有真正支持您的用例。这样做是为了允许一个线程中的迭代与其他线程中的修改同时发生。

如果这是您使用 ConcurrentHashMap 的唯一原因,那么您可能应该重新考虑,因为它比 HashMap 贵很多。你最好在像这样使用之前复制密钥集:

Map<String, Object> myData = new HashMap<String, Object>();
myData.put("A", 1);
myData.put("B", 2);
for(String key: myData.keySet().toArray(new String[0]))
    myData.remove(key);