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/