Video in progress

What is the difference between fail-fast and weakly consistent iterators?

A fail-fast iterator (ArrayList, HashMap) throws a ConcurrentModificationException right away if it notices the underlying collection changed. A weakly consistent iterator (ConcurrentHashMap, ConcurrentLinkedQueue) throws no exception and may see only some of the changes made during iteration.

📖 Answer

The fail-fast mechanism relies on modCount. It is "best effort", not a guarantee. In a multithreaded setting, HashMap can even return a wrong result without throwing. So treat a CME as a bug-finding aid, not as thread-safety.

Map<String, Integer> chm = new ConcurrentHashMap<>(Map.of("a", 1, "b", 2));
for (String k : chm.keySet()) {
    chm.put(k + "x", 0);    // no exception
}

This code works, but there is no guarantee that newly added keys are visible in this same loop. Sometimes they are, sometimes they aren't, depending on how the buckets are laid out.

The third kind is the snapshot iterator (CopyOnWriteArrayList): it sees the state from the moment it was created and never sees later changes.

Kind Example On modification
fail-fast ArrayList, HashMap, TreeMap CME (usually)
weakly consistent ConcurrentHashMap, ConcurrentSkipListMap keeps going, sees changes partially
snapshot CopyOnWriteArrayList sees the old snapshot