When I first encounter with these terminology, some questions arise in my mind about fail-fast and fail-safe , in initial days. When we add anything while iterating we encounter
ConcurrentModificationException, specially , when we delete element from collection while iterating using for-each loop of jdk 5. I hope every developer in their life must encounter
ConcurrentModificationException. The concept of fail-safe terminology in java iterator is new. First introduced with Concurrent Collections in Java 5 e.g.
fail-fast iterator in Java
fail-fast iterator throws
ConcurrentModificationException , if you try to change its structure. it means, fail-fast iterators fail as soon as they realized that structure of
Collection has been changed since iteration has begun. Here, structural changes means what? it means, removing, adding, updating any element from collection, while one thread is iterating over that collection.
How it works internally? it works on a flag counter, it’s implemented by keeping a modification count and if iteration thread realizes the change in modification count it throws
fail-safe iterator Java
fail-safe iterator doesn’t throw any
Exception , if Collection is modified structurally while iterating. Why it does’t throw Exception? just because , they work on clone (copy) of Collection instead of original collection and that is why they are called as fail-safe iterator. Iterator of
CopyOnWriteArrayList are an example of fail-safe iterator. Iterator written by
ConcurrentHashMap keySet is also fail-safe iterator and never throw
ConcurrentModificationException in Java.