gpt4 book ai didi

java - 如果我删除下一个对象,ConcurrentHashMap 返回 null

转载 作者:行者123 更新时间:2023-11-30 06:10:39 25 4
gpt4 key购买 nike

我正在尝试了解故障安全迭代器的工作原理。我在并发 HashMap 中遇到了一些奇怪的事情。代码如下--

    ConcurrentHashMap<String,String> hm = new ConcurrentHashMap<String,String>();
hm.put("name1", "value1");
hm.put("name2", "value2");
hm.put("name3", "value3");

Iterator<String> itr = hm.keySet().iterator();
int index = 0;
while(itr.hasNext()) {
System.out.println(hm.get(itr.next()));
hm.put(index+"1", index+"2");
hm.remove("name2");
index++;
}
System.out.println("--- Second iteration --- ");
Iterator<String> itr2 = hm.keySet().iterator();
while(itr2.hasNext()) {
System.out.println(hm.get(itr2.next()));
}

打印:

    value3
null
value1
--- Second iteration ---
12
02
value3
value1
22

我很困惑为什么在第一种情况下删除元素会更新,而添加却没有!我使用的是 1.8 运行时环境。

最佳答案

这是因为 ConcurrentHashMap 的迭代器在编辑 Map 时不会抛出 ConcurrentModificationException

该映射不会抛出此异常,而是返回反射(reflect)自创建迭代器以来某个时间跨度和当前时间存在的键/值。 javadoc 中也说明了这一点:

Retrieval operations (including get) generally do not block, so may overlap with update operations (including put and remove). Retrievals reflect the results of the most recently completed update operations holding upon their onset. For aggregate operations such as putAll and clear, concurrent retrievals may reflect insertion or removal of only some entries. Similarly, Iterators 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. However, iterators are designed to be used by only one thread at a time.

如果你需要同时使用值和键,而不会引起这样的错误,你应该遍历 map 的入口集而不是键集,这可以通过以下方式完成:

Iterator<Map.Entry<String,String>> itr = hm.entrySet().iterator();
int index = 0;
while(itr.hasNext()) {
Map.Entry<String,String> next = itr.next();
System.out.println(next.getValue());
hm.put(index+"1", index+"2");
hm.remove("name2");
index++;
}

关于java - 如果我删除下一个对象,ConcurrentHashMap 返回 null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35621663/

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