gpt4 book ai didi

java - ConcurrentHashMap 的迭代器给出奇怪的结果

转载 作者:行者123 更新时间:2023-11-29 08:39:25 26 4
gpt4 key购买 nike

ConcurrentHashMap 是线程安全的。因此,如果在迭代时向 map 添加任何值,则不应考虑它们。下面是我的代码:

public class Test {
public static void main(String[] args) {
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
map.put("ONE", 1);
map.put("TWO", 2);
Iterator<String> it = map.keySet().iterator();
while (it.hasNext()) {
String key = (String) it.next();
System.out.println(key + " : " + map.get(key));
map.put("9", 10); // This should not be reflected in the Iterator
map.put("5", 10); // This should not be reflected in the Iterator
}
}
}

输出:

    TWO : 2
ONE : 1
9 : 10

我的问题是为什么迭代器考虑 map.put("9", 10);

最佳答案

ConcurrentHashMap is thread safe. So if am adding any values to map at the time of iterating, it should not consider them.

这是不正确的。这就是javadoc说:

"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 are guaranteed to traverse elements as they existed upon construction exactly once, and may (but are not guaranteed to) reflect any modifications subsequent to construction."


简而言之,您期望 javadoc 显然没有说它们具有的迭代器属性。

关于java - ConcurrentHashMap 的迭代器给出奇怪的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41439073/

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