skip to content

What happens when you call Iterator.remove() on a fail-fast, a weakly consistent and a snapshot iterator in Java, with examples of each?

level: seniorimportance: should knowfreq 55%

answer

  1. remove() is an optional operation
  2. fail-fast: re-syncs expectedModCount
  3. other iterators fail at their next check
  4. weakly consistent: supported, no CME
  5. CopyOnWrite: UnsupportedOperationException

basics

~10 s

Iterator.remove() works on fail-fast iterators (ArrayList, HashMap) and keeps them in sync. It also works on weakly consistent ones (ConcurrentHashMap), with no ConcurrentModificationException. Snapshot iterators (CopyOnWriteArrayList) refuse it with UnsupportedOperationException.

solid answer

~40 s

Iterator.remove() is an optional operation, and what it does depends on the kind of iterator. On a fail-fast iterator, from the general-purpose java.util collections such as ArrayList or HashMap, it deletes the last returned element and re-syncs the iterator's expected modCount, so this iterator carries on while any other iterator on that collection fails at its next check. On a weakly consistent iterator, such as ConcurrentHashMap's or ConcurrentLinkedQueue's, it also deletes from the live collection, other threads may be writing at the same time, and no ConcurrentModificationException is thrown. A snapshot iterator, from CopyOnWriteArrayList or CopyOnWriteArraySet, walks an array captured at creation and refuses with UnsupportedOperationException, so you change the list itself instead. 'Fail-safe' is the colloquial name for the last two; the JDK's terms are weakly consistent and snapshot.

go deeper

for a junior

Know that the iterator's remove() is the safe way to delete from an ordinary collection during a loop, and that not every iterator supports it.

for a middle

Explain that remove() re-syncs expectedModCount on a fail-fast iterator, and name iterators that refuse it (CopyOnWriteArrayList) or allow it under concurrency (ConcurrentHashMap).

for a senior

Distinguish snapshot from weakly consistent iterators by what remove() does on each, explain why a second iterator fails after the first removes, and say why CME is best-effort.

for a principal

Choose the right collection for a concurrency/throughput profile (read-mostly vs write-heavy), reason about the memory/GC cost of copy-on-write when removals are frequent, consistency semantics for callers, and when external locking beats either.

## The contract `Iterator.remove()` removes from the underlying collection the last element this iterator returned, and can be called once per `next()`. It is an **optional operation**: an iterator that does not support it throws `UnsupportedOperationException`. What happens beyond that depends on which of three kinds of iterator you hold. "Fail-safe" is a popular name for the last two, but the Javadoc's terms are **weakly consistent** and **snapshot**. ## Fail-fast iterators: this iterator stays in sync Used by the general-purpose collections in **`java.util`** — `ArrayList`, `LinkedList`, `HashMap`, `HashSet`, `TreeMap`, etc. Most of them keep a **`modCount`** field (`HashSet` through its backing `HashMap`; `ArrayDeque` checks its array state instead), incremented on every *structural modification* (an add, a remove, or another change that could disturb iteration). An iterator copies it into `expectedModCount` when created and compares the two on `next()`, through `checkForComodification()` in `ArrayList`. `remove()` is the sanctioned edit: - It deletes the last returned element and sets `expectedModCount = modCount`, so **this** iterator carries on. - Any **other** iterator on the same collection still holds the old count and throws **`ConcurrentModificationException`** (CME) at its next check. - On `ArrayList`, `LinkedList`, `HashMap` and `TreeMap` it runs the check first, so it throws CME itself if something else modified the collection since this iterator last synced. - The check is **best-effort**, because it is not synchronized: in a true multithreaded race it may miss the modification. `remove()` does not make the collection thread-safe. ## Weakly consistent iterators: supported, with no CME Used by `ConcurrentHashMap`, `ConcurrentLinkedQueue`, `ConcurrentSkipListMap` and most other collections in **`java.util.concurrent`**, and in `java.util` by `EnumMap` and `EnumSet`. They never throw CME. The concurrent collections' iterators traverse elements as they existed at construction exactly once and *may* reflect later modifications. `remove()` deletes from the live collection: - On the concurrent collections other threads may be reading and writing meanwhile, and neither this iterator nor any other throws CME. - `ConcurrentHashMap`'s removes by key: whatever mapping holds that key by then goes, even if its value has changed since `next()` returned it. - A key removed and re-added during the walk can come round again, because the 'exactly once' covers what existed at construction. - `ConcurrentHashMap`'s iterators are designed to be used by only one thread at a time: the traversal tolerates other threads' writes, but the iterator object is not for sharing. ## Snapshot iterators: refused `CopyOnWriteArrayList` and `CopyOnWriteArraySet` copy the whole backing array on every mutation, and the iterator holds a reference to the array *as it was when the iterator was created*. So `remove()`, and on a `ListIterator` `set()` and `add()`, throw `UnsupportedOperationException`. Change the list itself instead. `list.remove(x)` during the loop is safe and this iterator never sees it, at the cost of an array copy per removal; `list.removeIf(...)` removes them all with one copy. ## Side by side | Aspect | Fail-fast (general-purpose `java.util`) | Weakly consistent | Snapshot (copy-on-write) | |---|---|---|---| | `Iterator.remove()` | supported | supported | `UnsupportedOperationException` | | Other iterators afterwards | CME at their next check | no CME | not applicable | | Removing through the collection instead | CME at this iterator's next check, usually | no CME; this iterator may or may not see it | no CME; this iterator never sees it | | Examples | `ArrayList`, `HashMap` | `ConcurrentHashMap`, `ConcurrentLinkedQueue` | `CopyOnWriteArrayList` | ## Example ```java // Fail-fast: this iterator survives its own remove(), another does not List<Integer> a = new ArrayList<>(List.of(1, 2, 3)); Iterator<Integer> it = a.iterator(); Iterator<Integer> other = a.iterator(); it.next(); it.remove(); // a is now [2, 3] it.next(); // fine, returns 2 // other.next() here would throw ConcurrentModificationException // Weakly consistent: supported, with no exception Map<String, Integer> m = new ConcurrentHashMap<>(Map.of("x", 1)); Iterator<String> keys = m.keySet().iterator(); keys.next(); keys.remove(); // m is now empty // Snapshot: refused, so change the list itself List<Integer> b = new CopyOnWriteArrayList<>(List.of(1, 2, 3)); Iterator<Integer> snap = b.iterator(); snap.next(); // snap.remove() here would throw UnsupportedOperationException b.remove(Integer.valueOf(1)); // b is now [2, 3]; snap still has 2 and 3 to walk ``` ## Term recap - **Optional operation**: a method the interface declares but an implementation may refuse with `UnsupportedOperationException`. - **Structural modification**: an add, a remove or another change that perturbs iteration (not `set` of an existing slot). - **modCount / expectedModCount**: counters whose mismatch triggers CME. - **Best-effort**: detection that may miss a race; not a guarantee. - **Snapshot iterator**: iterates the array as it was at creation, under copy-on-write. - **Weakly consistent**: never throws CME, may reflect later changes, and traverses what existed at construction exactly once.

  • After it.remove() on an ArrayList, what happens to a second iterator opened before the removal?
    It throws ConcurrentModificationException at its next next(). it.remove() re-synced only its own expectedModCount, and the list's modCount has moved on.
  • If another thread changes a key's value between next() and remove() on a ConcurrentHashMap iterator, what gets removed?
    The mapping for that key, whatever its value is by then: the iterator's remove calls the map's replaceNode with the key and no expected value. Use map.remove(key, value) if the value must still match.

  • Believing Iterator.remove() works on every iterator (it is optional, and CopyOnWriteArrayList's refuses it)
  • Thinking Iterator.remove() makes a fail-fast collection safe to share across threads
  • Assuming a second iterator on the same ArrayList survives the first iterator's remove()
  • Treating 'fail-safe' as a strict guarantee of a consistent view (it's snapshot or weakly consistent)
  • Thinking ConcurrentHashMap's iterator snapshots the whole map like COW does

Iterator
Java 1.2
ConcurrentHashMap
Java 1.5
CopyOnWriteArrayList
Java 1.5

context