Fail-fast iterators in Java throw ConcurrentModificationException exception if the collection is modified while iterating over it. Fail-safe iterators do not throw any exception even if the collection is modified while iterating over it.
Default iterators for Collections from java.util package such as ArrayList, HashMap, etc. are Fail-Fast.
Sample Java code to demonstrate Fail-fast iterators
public class FailFastExample { static public void main(String[] args) { ArrayList<Integer> numbers = new ArrayList<Integer>(); numbers.add(1); numbers.add(2); Iterator<Integer> iterator = numbers.iterator(); while (iterator.hasNext()) { Integer number = iterator.next(); numbers.add(50); } } } Exception in thread "main" java.util.ConcurrentModificationException at java.util.ArrayList$Itr.checkForComodification(ArrayList.java:909) at java.util.ArrayList$Itr.next(ArrayList.java:859) at FailFastExample.main(FailFastExample.java:12)
Fail Safe Iterator makes copy of the internal data structure (object array) and iterates over the copied data structure. Any structural modification done to the iterator affects the copied data structure. So original data structure remains structurally unchanged. Hence no ConcurrentModificationException throws by the fail safe iterator.
Iterators on Collections from java.util.concurrent package such as ConcurrentHashMap, CopyOnWriteArrayList, etc. are Fail-Safe in nature.
Sample Java code to demonstrate Fail-safe iterators
public class FailSafeExample { static public void main(String[] args) { ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>(); map.put("Dhoni", 7); map.put("Virat", 18); map.put("Chris", 333); map.put("Sachin", 10); Iterator<String> iterator = map.keySet().iterator(); while (iterator.hasNext()) { String key = iterator.next(); map.put("Bhuvneshvar", 1); } iterator = map.keySet().iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
Hope you have enjoyed reading Difference between Fail Fast and Fail Safe iterator in Java. Please do write us if you have any suggestion/comment or come across any error on this page. Thank you for reading!
Share this page on WhatsApp