Fail Fast vs Fail Safe Iterator in Java
When one or more thread is iterating over the collection, in between, one thread changes the structure of the collection is known as Concurrent Modification . The ConcurrentModificationException is thrown if the Collection is modified while Iterating over the data structure. Concept of fail-fast and fail-safe iterator are relatively new in Java and first introduced with Concurrent Collections in Java 5 like ConcurrentHashMap and CopyOnWriteArrayList. Java Collections supports two types of Iterator, Fail-Fast iterators and Fail-Safe Iterators.
Fail-Fast iterators, returned by most of the collection types, doesn't tolerate any structural modifications to a collection while iterating over it. In Java, a fail-fast iterator fails by throwing a ConcurrentModificationException . Structural changes means adding, removing or updating any element from collection while one thread is Iterating over that collection. fail-fast behaviour is implemented by keeping a modification count and if iteration thread realizes the change in modification count it throws
Contrary to fail-fast Iterator, fail-safe iterator doesn't throw any Exception if Collection is modified structurally while one thread is Iterating over it because they work on clone of Collection instead of original collection and that's why they are called as fail-safe iterator. So, any structural modifications done on the actual collection goes unnoticed by these iterators. Iterator of CopyOnWriteArrayList is an example of fail-safe Iterator also iterator written by ConcurrentHashMap keySet is also fail-safe iterator and never throw ConcurrentModificationException in Java.