Fail fast iterator while iterating through the collection, instantly throws java.util.ConcurrentModificationException if there is structural modification of the collection.
Thus, in the case of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.
In Single Threaded Environment
After the creation of the iterator, structure is modified at any time by any method other than iterator's own remove method.
The Collection is internally modified, while a thread is iterating over it.
After the creation of an iterator, the Collection is internally modified by any method other than the iterator’s own methods for removal and addition.
Multiple Threaded Environment
If one thread is modifying the structure of the collection while other thread is iterating over it.
Two iterators simultaneously modify the internal structure of a Collection.
The fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis.
Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs.
How Fail Fast Iterator come to know that the internal structure is modified:
Iterator read internal data structure (object array) directly. The internal data structure(i.e. object array) should not be modified while iterating through the collection.
To ensure this it maintains an internal flag "mods". Iterator checks the "mods" flag whenever it gets the next value (using hasNext() method and next() method).
Value of mods flag changes whenever there is an structural modification. Thus indicating iterator to throw ConcurrentModificationException.