What are fail-fast and fail-safe iterators in Java, and what happens when you modify a collection while iterating it?
A fail-fast iterator is one that notices when the collection is changed while it is being walked through, and it throws an exception rather than carrying on with results that cannot be trusted.
Most of the ordinary collections give you a fail-fast iterator. The ArrayList, the HashMap and the HashSet all do it, and the exception that they throw is called ConcurrentModificationException.
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;
public class Main {
public static void main(String[] args) {
List<String> names = new ArrayList<String>();
names.add("Ada");
names.add("Grace");
// The fail-fast iterator notices the change.
try {
for (String name : names) {
if (name.equals("Ada")) {
names.add("Alan");
}
}
} catch (ConcurrentModificationException e) {
System.out.println("fail fast : ConcurrentModificationException");
}
// The fail-safe iterator simply walks the copy it made.
List<String> safe = new CopyOnWriteArrayList<String>(names);
for (String name : safe) {
if (name.equals("Ada")) {
safe.add("Alan");
}
}
System.out.println("fail safe : " + safe);
}
}
A fail-safe iterator does not throw. It walks over a snapshot that was taken when the iterator was made, so it does not see any changes that happen while it is running. The CopyOnWriteArrayList works that way, because it keeps a copy of the array and makes a new one every time it is changed.
So what happens when you modify a collection while you are iterating it? With a fail-fast iterator, you get an exception that tells you the code is wrong. With a fail-safe iterator, the loop finishes over the old data and your change is not seen.
One honest detail is worth knowing. The fail-fast check is a best effort. The collection notices the change if it can, but the rules of the language do not promise that it always will, so you should never rely on catching the exception as part of your program logic.
The next question in this topic looks at which collections give you which kind of iterator.