Course contentsShow
← Java
Lesson 1157 of 2,87026. Map ImplementationsFree lesson

Iterators and ConcurrentModificationException

Explore how Hashtable's iterators behave under concurrent modification and fail-fast semantics.

Iterators and ConcurrentModificationException

What you'll learn: How Hashtable's iterators detect and respond when the map is modified during iteration.

The Fail-Fast Guarantee

When you obtain an iterator from a Hashtable (or most Java collections), that iterator takes a "snapshot" of the collection's modification count. If you then modify the Hashtable while iterating — adding, removing, or updating entries through the map itself (not through the iterator) — the iterator detects this and throws a ConcurrentModificationException.

This is called fail-fast behavior: the iterator fails immediately and predictably rather than risking unpredictable results.

Why This Matters

Imagine reading a book while someone tears out random pages. You'd want to know immediately, not discover missing content later! Similarly, iterators refuse to continue when the underlying collection changes unexpectedly.

Hashtable<String, Integer> scores = new Hashtable<>();
scores.put("Alice", 95);
scores.put("Bob", 87);
scores.put("Carol", 92);

Iterator<String> it = scores.keySet().iterator();
while (it.hasNext()) {
    String key = it.next();
    scores.put("Dave", 88);  // Modifying during iteration!
    // ConcurrentModificationException thrown here
}

Safe Modification During Iteration

The only safe way to modify during iteration is through the iterator's own remove() method:

Iterator<String> it = scores.keySet().iterator();
while (it.hasNext()) {
    String key = it.next();
    if (key.equals("Bob")) {
        it.remove();  // Safe: using iterator's method
    }
}

This works because the iterator updates its internal state to stay consistent.

Key Takeaway: Hashtable iterators are fail-fast — they throw ConcurrentModificationException if the map is modified during iteration (except through the iterator's own remove() method), protecting you from unpredictable behavior.