故障安全迭代器 - 在迭代期间移除

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());
}

根据文档,地图上的任何操作都将反映在键集上,反之亦然。并且 KeySet#iterator() 也不会克隆底层 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

正如 Javadoc for keySet() 中所说:

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

您的迭代器反映构造后的修改。