ConcurrentHashMap and Weakly Consistent Iterators
What You'll Learn
You'll understand how ConcurrentHashMap iterators behave differently from fail-fast iterators by being weakly consistent with concurrent modifications.
The Core Idea
While ArrayList and HashMap have fail-fast iterators that throw ConcurrentModificationException when detecting structural changes, ConcurrentHashMap takes a different approach. Its iterators are weakly consistent, meaning they reflect the state of the map at some point since the iterator was created, but they won't necessarily show all concurrent modifications.
Think of it like reading a newspaper during breaking news. The paper you're holding shows accurate information from when it was printed, but reporters are simultaneously writing new stories. You won't see those updates in your copy, but you also won't have your paper spontaneously burst into flames (no exception thrown).
How It Works
When you iterate over a ConcurrentHashMap:
- No exceptions: The iterator never throws
ConcurrentModificationException, even if other threads modify the map - Snapshot-like: Elements present when iteration began are guaranteed to be traversed exactly once
- May or may not reflect changes: Updates made by other threads during iteration might appear, or might not
- Always safe: You can read while others write, with no corruption or crashes
This "weak consistency" is a trade-off: you sacrifice the guarantee of seeing the absolute latest state for the benefit of allowing concurrent access without locking or exceptions.
Key Takeaway:
ConcurrentHashMap iterators are weakly consistent—they never fail with exceptions during concurrent modifications but may reflect an inconsistent snapshot mixing old and new data, prioritizing availability over strict consistency.