How fail fast iterator comes to know that the internal structure is modified?

Every fail fast collection has a modCount field, to represent how many times the collection has changed/modified. So at every modification of this collection we increment the modCount value. For example the modCount is incremented in below cases:

  1. When one or more elements are removed.
  2. When one or more elements are added.
  3. When the collection is replaced with other collection.
  4. When the collection is sorted.

So everytime there is some change in the collection structure, the mod count is incremented.

The iterator stores the modCount value in the initialization as below:

int expectedModCount = modCount;

While the iteration is going on, expectedModCount will have old value of modCount. If there is any change made in the collection, the modCOunt will change and then an exception is thrown using:

if (modCount != expectedModCount) throw new ConcurrentModificationException();

This code is used in most of the iterator methods:

1. next() 2. remove() 3. add()

So, if we make any changes to the collection, the modCount will change, and expectedModCount will not be hence equal to the modCount. Then if we use any of the above methods of iterator, the ConcurrentModificationException will be thrown.

Hope you have enjoyed reading How fail fast iterator comes to know that the internal structure is modified?. Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!



Share this page on WhatsApp

Get Free Tutorials by Email

About the Author

is the founder and main contributor for cs-fundamentals.com. He is a software professional (post graduated from BITS-Pilani) and loves writing technical articles on programming and data structures.