What is the difference between fail-fast and fail-safe iterators?

Fail-fast iterators (ArrayList, HashMap) check a modification counter and throw ConcurrentModificationException when the collection is changed in the loop. Fail-safe (weakly consistent) iterators, like those of CopyOnWriteArrayList and ConcurrentHashMap, do not throw.

import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

public class Main {
    public static void main(String[] args) {
        List<Integer> failFast = new ArrayList<>(List.of(1, 2, 3, 4));
        try {
            for (Integer n : failFast) {
                if (n == 1) failFast.add(99);
            }
        } catch (java.util.ConcurrentModificationException e) {
            System.out.println("ArrayList: ConcurrentModificationException");
        }

        List<Integer> failSafe = new CopyOnWriteArrayList<>(List.of(1, 2, 3, 4));
        for (Integer n : failSafe) {
            if (n == 1) failSafe.add(99);
        }
        System.out.println("CopyOnWriteArrayList: " + failSafe);
    }
}
Output

ArrayList: ConcurrentModificationException
CopyOnWriteArrayList: [1, 2, 3, 4, 99]

To remove items while looping, use removeIf() or the remove() of the iterator.


Learn more about the similar topics:
Tutorials
No Content Found.
Exercises & Assignments
No Content Found.
Interview Questions & Answers
No Content Found.