gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-01 22:37:34 25 4
gpt4 key购买 nike

我正在尝试了解 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 昂贵得多。你最好在像这样使用之前复制 key 集:

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);

关于java - 对本例中 ConcurrentHashMap 和 HashMap 行为的区别感到困惑,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54755650/

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