Iterators and Weakly Consistent Views
What you'll learn: How ConcurrentHashMap's iterators behave differently from regular collections, reflecting a snapshot view without throwing exceptions during concurrent modifications.
The Problem with Regular Iterators
When you learned about Hashtable and ConcurrentModificationException, you saw that traditional collections fail-fast: their iterators throw exceptions if the collection changes while you're iterating. This makes concurrent programming difficult.
ConcurrentHashMap's Solution: Weakly Consistent Iterators
ConcurrentHashMap takes a different approach. Its iterators are weakly consistent, meaning:
- They reflect a snapshot of the map at (or near) the time the iterator was created
- They never throw ConcurrentModificationException, even if the map changes during iteration
- They may or may not reflect concurrent updates made after iterator creation
Think of it like taking a photograph of a busy street. The photo shows the street as it was when you clicked the shutter. People might move or leave afterward, but your photo doesn't change—and it certainly doesn't self-destruct if someone walks away!
Example Behavior
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
// Create iterator - captures approximate current state
Iterator<String> iter = map.keySet().iterator();
// These changes might or might not appear during iteration
map.put("D", 4);
map.remove("B");
// No exception thrown, iteration proceeds safely
while (iter.hasNext()) {
System.out.println(iter.next());
}
The iterator won't crash, but whether "D" appears or "B" is skipped depends on timing—it's "weakly consistent."
Key Takeaway: ConcurrentHashMap iterators provide a stable, exception-free way to traverse the map during concurrent modifications, trading perfect accuracy for reliability and performance.