I know what is a fail-fast and fail-safe iterator. Fail-Fast iterators immediately throw ConcurrentModificationException if there is a structural modification of the collection.
Fail-Safe doesn't throw any exception as they work on a clone of collection.
My question is how does a fail-fast iterator come to know that a modification is made to my collection?
You can check the implementation yourself.
Let's consider ArrayList
as an example.
It has an inner Itr
class, which the iterator()
method returns an instance of.
The Itr
class has an expectedModCount
counter, which is initialized with the enclosing ArrayList
's modCount
:
private class Itr implements Iterator<E> {
int cursor; // index of next element to return
int lastRet = -1; // index of last element returned; -1 if no such
int expectedModCount = modCount;
...
}
When you call methods of the Iterator
, such as next()
or remove()
, it calls the checkForComodification()
method:
final void checkForComodification() {
if (modCount != expectedModCount)
throw new ConcurrentModificationException();
}
which throws an exception if the ArrayList
's modCount
has incremented since the Iterator
instance was created.