JAGRITI BANSAL
JAGRITI BANSAL

Reputation: 109

How Fail-fast Iterator works internally?

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?

Upvotes: 1

Views: 711

Answers (2)

Eran
Eran

Reputation: 394086

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.

Upvotes: 3

Andy Turner
Andy Turner

Reputation: 140514

There is no single way to implement this.

In the case of ArrayList (and other classes in java.util), the iterator keeps an int expectedModCount ("expected modification count"), which it compares to the AbstractList's int modCount ("modification count"), which gets updated whenever there is a structural modification to the list; the iterator throws an exception if the two values are different.

Upvotes: 0

Related Questions