In this tutorial we will learn what is Fail Fast what is Fail Safe Iterator in java .
This is the one of the main question in interview regarding Concurrency management.Before looking into “Fail Fast vs Fail Safe” we should aware of the term “Concurrent Modification”
What is Concurrent Modification ?
Is nothing but one or more threads try modify the structure of the collection
(i.e adding or deleting or updating element to collection) parallelly is know as Concurrent Modification.
Fail Fast Iterator Example
Fail fast Iterator throws Concurrent Modification Exception if there is
structural modification of the collection while iterating the collection.see the below example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
import java.util.HashMap; import java.util.Iterator; import java.util.Map; public class FailFastInJava { public static void main(String[] args) { Map<String,String> employee = new HashMap<String,String>(); employee.put("Ramesh", "TL"); employee.put("Sreenath", "TL"); employee.put("Alex","PM"); Iterator iterator = employee.keySet().iterator(); while (iterator.hasNext()) { System.out.println(employee.get(iterator.next())); employee.put("Ravi", "PM"); } } } |
when we try to add “Ravi ” to collection we get below exception.
1 2 3 4 5 6 7 8 9 |
TL Exception in thread "main" java.util.ConcurrentModificationException at java.util.HashMap$HashIterator.nextEntry(Unknown Source) at java.util.HashMap$KeyIterator.next(Unknown Source) at FailFastInJava.main(FailFastInJava.java:20) |
Fail SafeIterator Example
Fail safe Iterator will not throws Concurrent Modification Exception if there is
structural modification of the collection while iterating the collection.see the below example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
import java.util.HashMap; import java.util.Iterator; import java.util.concurrent.ConcurrentHashMap; public class FailSafeInJava { public static void main(String[] args) { ConcurrentHashMap<String,String> employee = new ConcurrentHashMap<String,String>(); employee.put("Ramesh", "TL"); employee.put("Sreenath", "TL"); employee.put("Alex","PM"); //First iteration Iterator firsIterator = employee.keySet().iterator(); while (firsIterator.hasNext()) { System.out.println(employee.get(firsIterator.next())); employee.put("Ravi", "CEO"); } System.out.println("************In second iteration **************"); //Second iteration after adding "Ravi" to collection Iterator secondIterator = employee.keySet().iterator(); while (secondIterator.hasNext()) { System.out.println(employee.get(secondIterator.next())); } } } |
But here if you try to add “Ravi ” to collection we will not get any exception.
OUT PUT:
1 2 3 4 5 6 7 8 9 10 11 12 |
TL TL PM ************In second iteration ************** CEO TL TL PM |