I played with java.util.HashMapto find out what this behavior is 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));
}
I got the result
12
11
10
14
13
after modifn
12
11
10
14
I also tried using an iterator
Iterator<String> itr = keys.iterator();
while(itr.hasNext()) {
String key = itr.next();
if(key.equals("stark")) {
map.remove(key);
}
}
I have not received any ConcurrentModificationExceptionin any way. This is because (from javadoc)
the fault-tolerant behavior of the iterator cannot be guaranteed, as it is, generally speaking, it is impossible to make any serious guarantees for the presence of an unsynchronized parallel modification. Normal-fast iterators throw ConcurrentModificationException in the best possible way
I checked another thread that says it will quit ConcurrentModificationException.. what do you think?
source
share