Fail Fast And Fail Safe Iterators in Java
This Concepts come under the Concurrent Modification.
Fail Fast Iterators
Java iterators are used to loop through Collection objects. If the collection has undergone structural modification, Fail-Fast iterators instantly throw ConcurrentModificationException.
While a thread is iterating across a collection, structural modification is the addition or removal of any member from that collection.
A few of examples of fail-fast iterators are the ArrayList and HashMap classes.
public class FailFastIteratorExample {
public static void main(String[] args)
{
Map<String,String> city = new HashMap<>();
cityCode.put("Delhi", "India");
cityCode.put("Moscow", "Russia");
cityCode.put("New York", "USA");
Iterator iterator = city.keySet().iterator();
while (iterator.hasNext()) {
System.out.println(city.get(iterator.next()));
city.put("Istanbul", "Turkey"); // this will throw exception when trying to print the next value
}
}
}
Fail Safe Iterators
When iterating over a collection that has undergone structural change, fail-safe iterators do not throw any exceptions.
They are known as fail-safe iterators because they work on a copy of the collection rather than the original collection.
Examples of fail-safe iterators are ConcurrentHashMap and the iterator on CopyOnWriteArrayList.
public class FailSafeItreratorExampple {
public static void main(String[] args)
{
ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<>();
map.put("ONE", 1);
map.put("TWO", 2);
map.put("THREE", 3);
map.put("FOUR", 4);
Iterator it = map.keySet().iterator();
while (it.hasNext()) {
String key = (String)it.next();
System.out.println(key + " : " + map.get(key));
map.put("SEVEN", 7); // this will not throw any exception
}
}}
Comments
Post a Comment