I Built My Own Fail-Fast HashMap — Here's Why a Boolean Flag Wasn't Enough
If you've done LeetCode's Design HashMap , you've implemented put , get , and remove . What that exercise usually skips is the part that actually breaks in production: what happens when someone mutates the map while another piece of code is iterating over it. I ran into this directly while building MyHashMap , a from-scratch single-threaded HashMap (separate chaining, resize on load factor). Getting put / get / remove right was the easy 80%. Getting entrySet().iterator() to correctly detect concurrent mutation — including the case where a second, completely separate iterator is the one that should notice — took three wrong turns before landing on the pattern the JDK actually uses. The problem, concretely Iterator < Entry < K , V >> it = map . entrySet (). iterator (); it . next (); map . put ( someNewKey , someValue ); // structural change, mid-iteration it . next (); // ??? — undefined behavior if we don't guard against this Without a guard, next() might return a stale entry, skip entries entirely, or throw an unrelated exception depending on internal bucket-array state. Java's real collections handle this with ConcurrentModificationException (CME) — but the interesting part isn't the exception, it's the mechanism that detects when to throw it. First idea: a boolean "dirty" flag Obvious first attempt: a boolean modified field on the map, flipped to true on any put / remove , checked by the iterator. This works for exactly one iterator. It falls apart the moment two iterators are alive at once: Iterator A calls next() , sees modified == false , proceeds. Something else mutates the map. modified flips to true . Iterator B — created after that mutation — checks the same shared modified flag, sees true , and incorrectly throws, even though nothing has changed since B was created. A single shared boolean can't represent "changed since this specific iterator was created" for more than one iterator at a time. Resetting it on read doesn't help either — now the other iterat