我尝试使用 java.util.HashMap
来了解什么是fail-fast
行为。
HashMap map = new HashMap();
map.put("jon", 10);
map.put("sean", 11);
map.put("jim", 12);
map.put("stark", 13);
map.put("vic", 14);
Set keys = map.keySet();
for(Object k:keys) {
System.out.println(map.get(k));
}
for(Object k:keys) {
String key =(String)k;
if(key.equals("stark")) {
map.remove(key);
}
}
System.out.println("after modifn");
for(Object k:keys) {
System.out.println(map.get(k));
}
我得到了结果
12
11
10
14
13
after modifn
12
11
10
14
我也试过使用迭代器
Iterator<String> itr = keys.iterator();
while(itr.hasNext()) {
String key = itr.next();
if(key.equals("stark")) {
map.remove(key);
}
}
在这两种情况下我都没有得到任何 ConcurrentModificationException
..这是因为(来自 javadoc)
the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis
我检查了另一个 thread它说,它会抛出 ConcurrentModificationException
..你怎么看?
最佳答案
鉴于您显示的输出:
12
11
10
14
13 // notice this?
after modifn
12
11
10
14
因为 13 是最后一个键值对,当您 Iterate
通过你的HashMap
然后最后去掉stark 13
对应的key-value ,这会停止 Iteration
在 HashMap
之后已被修改,因此,它不会 iterate
了。所以没有 ConcurrentModificationException.
关于java - java HashMap 的快速失败行为,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11094139/