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
Java ArrayList
Java HashMap
Java HashSet and LinkedList
Java Generics
Exercises & Assignments
Sort a list of students with a Comparator
Count the frequency of words with a HashMap
Remove duplicates from a list and keep the order
Interview Questions & Answers
What is the difference between an array and an ArrayList in Java?
How does HashMap work internally in Java?
What is the difference between HashMap, Hashtable and ConcurrentHashMap?
Why must you override both equals() and hashCode() in Java?
What is the difference between Comparable and Comparator in Java?
What is the difference between ArrayList and LinkedList in Java?
What is the difference between fail-fast and fail-safe iterators?