Learn different aspects of fail-fast vs fail-safe iterator in Java. In Java fail-fast iterator and fail-safe iterator intent are same to some extent but one abort operations another not abort.
1. Overview of fail-fast vs fail-safe iterator in Java
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. ConcurrentHashMap
and CopyOnWriteArrayList
.
2. fail-fast iterator in Java
In order to understand fail-fast vs fail-safe iterator in Java, you have to understand one of them individually. 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 ConcurrentModificationException
.
3. 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.
4. fail-fast vs fail-safe iterator in Java
- Fail-Fast systems abort operation as fast-as-possible exposing failures immediately and stopping the whole operation.
- fail-safe systems don’t abort an operation in the case of a failure. Such systems try to avoid raising failures as much as possible.
5. Reference
docs.oracle.com for more details.
visit Core Java tutorial for more details
Pingback: Radhika