-2

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());
}
Azodious
  • 13,752
  • 1
  • 36
  • 71

2 Answers2

1

As per documentation any operation on map will reflect on keyset and vice versa. And KeySet#iterator() also does not clone the underlying ds.

ConcurrentHashMap#keySet():

Returns a Set view of the keys contained in this map. The set is backed by the map, so changes to the map are reflected in the set, and vice-versa. The set supports element removal, which removes the corresponding mapping from this map, via the Iterator.remove, Set.remove, removeAll, retainAll, and clear operations.

Read more documentation

See openjdk Implementation

Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103
  • It's more specific than the `keySet()`: it's the `keySet().iterator()` which is being used here. – Andy Turner Jun 03 '16 at 14:01
  • ohk. One sec, what I can see `KeySet#iterator()` returns `KeyIterator` which is also does not clone the underlaying ds too. :) [reference](http://grepcode.com/file/repository.grepcode.com/java/root/jdk/openjdk/6-b14/java/util/concurrent/ConcurrentHashMap.java) – Subhrajyoti Majumder Jun 03 '16 at 14:05
1

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243