Search code examples
javacollectionsiteratorconcurrenthashmap

Fail safe iterator - removal during iteration


If fail safe iterator creates a clone of underlying data structure, why 'D' is never printed in program below?

Map<String, String> acMap = new ConcurrentHashMap<String, String>();
acMap.put("A", "Aye");
acMap.put("B", "Bee");
acMap.put("C", "See");
acMap.put("D", "Di");

Iterator<String> itr = acMap.keySet().iterator();
while(itr.hasNext())
{
    acMap.remove("D");
    System.out.println(itr.next());
}

Solution

  • As it says in the Javadoc for keySet():

    The iterator ... may (but is not guaranteed to) reflect any modifications subsequent to construction.

    Your iterator is reflecting modifications subsequent to construction.