What do you understand by iterator fail-fast property
Answer : Java Iterator is fail fast by design and it’s sole purpose is to iterate a collection in forward direction only. It checks the failure condition aggressively and throw “java.util.ConcurrentModificationException” if during iteration collection been modified before more damage happens.
Note: All collection classes in java.util package are fail fast and java.util.concurrent package are fail safe.
Fail fast algorithm is implemented using a volatile counter on the list object:
- Whenever iterator is created the current value of the counter will be added to the iterator object
- If list is update then counter will be incremented
- During iteration operation method compares two counter values and throw exception
Please example below: