1

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?

  • 1
    I would like to encourage you to write a small method and try to implement a behavior so that it will throw exception on some predefined conditions. Or As soon as the condition meet method should stop executing and throw exception. – madhepurian Oct 02 '19 at 11:58
  • @madhepurian Thanks for idea, will definetly try it :) – JAGRITI BANSAL Oct 02 '19 at 12:02
  • "how? " there is an `int` counter that is incremented by each method that does a *structural* modification. Each relevant iterator operation checks this value against the value of the counter stored when the iterator is created. See documentation of `AbstractList` field [modCount](https://docs.oracle.com/en/java/javase/13/docs/api/java.base/java/util/AbstractList.html#modCount) (or its source code) – user85421 Oct 02 '19 at 12:36

2 Answers2

3

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.

Eran
  • 387,369
  • 54
  • 702
  • 768
0

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.

Andy Turner
  • 137,514
  • 11
  • 162
  • 243