Search code examples
javahashmapconcurrentmodification

fail fast behaviour of java HashMap


I played around with java.util.HashMap to learn what the fail-fast behaviour is.

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 didn't get any ConcurrentModificationException in either case ..Is this because (from 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

I checked another thread which says ,it WILL throw ConcurrentModificationException..what do you think?


Solution

  • Given the output that you have shown:

    12
    11
    10
    14
    13   // notice this?
    after modifn
    12
    11
    10
    14
    

    Since 13 is the last key-value pair, when you Iterate through your HashMap and then finally remove the key-value corresponding to stark 13, that stops the Iteration just after the HashMap has been modified, hence, it doesn't iterate anymore. So no ConcurrentModificationException.