Why a Boolean Flag Fails for Fail-Fast Iterators: A Custom HashMap Deep Dive
A developer building a from-scratch single-threaded HashMap in Java found that implementing basic operations like put, get, and remove was straightforward, but correctly detecting concurrent mutation during iteration proved far more complex. An initial approach using a shared boolean flag failed when multiple iterators existed simultaneously, as one iterator could incorrectly throw a ConcurrentModificationException based on changes that occurred before it was created. A timestamp-based alternative also fell short due to clock resolution issues and the non-monotonic nature of system clocks. The correct solution, mirroring the JDK's own approach, uses a plain incrementing version counter on the map, with each iterator snapshotting the counter value at creation and comparing it on every next() call. This ensures each iterator independently detects only structural changes that occurred after it was created, without relying on shared state or wall-clock time.
This is an AI-generated summary. ShortSingh links to the original source for the complete article.
Discussion (0)
Log in to join the discussion and vote.
Log in