fail fast iterator

The following two tabs change content below.
Prasad Kharkar is a java enthusiast and always keen to explore and learn java technologies. He is SCJP,OCPWCD, OCEJPAD and aspires to be java architect.

Latest posts by Prasad Kharkar (see all)

We know that iterators are used for iterating over collections in java. They provide is ways to move through the collections. Some java collections use fail fast approach so that an exception is thrown when collection is structurally modified after iterator is created from it. We will understand fail fast iterator in detail in this article.

Fail Fast Iterator

Fail fast iterator means that it may fail and when it fails, iterator fails and quickly. rather than having risk of undetermined risk in future due to modification. We’ve seen that after modifying a collection after iterator is created, it gives ConcurrentModificationException. Let us try to understand the implementation of a fail fast iterator.

Implementation of Fail Fast Iterator

Usually a fail fast iterator is implemented using a count of the modifications in collection and expected count of modifications. If expected count and actual count is not matching then the iterator fails and ConcurrentModificationException is thrown. Let us try to understand it with the help of an example.

Example of Fail Fast Iterator

Here we will simply try to add some elements into a list and iterate over it. Here is our sample program.

The output is,

  • ArrayList class has instance variable modCount, which gets incremented everytime an element is added or removed, so in above program when 5 elements are added then modCount=5.
  • Iterator iterator = integers.iterator(); creates an instance of Iterator . As soon as it is created, its instance variable expectedModCount, is populated with modCount, so now expectedModCount=5.
  • Now, every time call is made, it checks whether expectedModCount is equal to modCount, if it is not matching, then ConcurrentModificationException is thrown.
  • Above code tries to remove element 2 and it removes successfully.
  • Note that ArrayList.remove method removes the element and increases the modCount variable. so, now modCount=6 but expectedModCount=5 because expectedModCount is assigned the the value when Iterator is instantiated and it retains that value only. i.e.5
  • Now there is a mismatch between modCount and expectedModCount and when method is called, ConcurrentModificationException will be thrown.

I hope the article helped understand how fail fast iterator is implemented generally in collections framework.

Share Button

Leave a Reply

Your email address will not be published. Required fields are marked *