Fail-Fast iterators throw ConcurrentModificationException if the Collection is modified structurally. Fail-Fast iterators fail quickly and cleanly rather than risking the arbitrary non-deterministic behavior at undetermined time in future.
Now Fail-Fast iterators can throw ConcurrentModificationException in two situations:
- Single threaded environment: Once iterator is created and you don’t use remove method of iterator to remove element from Collection. Also if you use add method while iterating over collection then also ConcurrentModificationException is thrown.
- Multithreaded Environment: If one thread is iterating over the collection and another thread modifies the collection structurally.
This leads to one more question: How does the iterator comes to know that internal structure is modified?
- There is a int value called modCount. Whenever the Collection is modified structurally the modCount is incremented. next() method and remove() method of Iterator calls checkForComodification() method which checks modCount and expectedModCount are same or not. If not then ConcurrentModificationException is thrown.
List<Integer> numbers = Arrays.asList(1, 2, 3, 4, 5); Iterator<Integer> iterator = numbers.iterator(); while(iterator.hasNext()) { iterator.next(); iterator.remove(2); } Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(Unknown Source) at java.util.ArrayList$Itr.next(Unknown Source)
In this article, we saw that fail-fast iterators can throw ConcurrentModificationException if the Collection is modified structurally while iterating.