When an iterator is created, either it is directly created on the collection (Fail Fast), or created on a clone of that collection (Fail Safe).This brings below two types of Iterator.
Fail Fast :
As name suggest fail-fast Iterators fail as soon as they realized that structure of Collection has been modified since iteration has begun, if the iterator thread realizes the modification ,then it throws ConcurrentModificationException. Changes can be additions, updation or deletion. This behavior (fail-fast) is implemented by keeping a modification count.
From API
Note that the fail-fast behavior of an iterator cannot be guaranteed as it is, generally speaking, impossible to make any hard guarantees in the presence of unsynchronized concurrent modification. Fail-fast iterators throw ConcurrentModificationException on a best-effort basis. Therefore, it would be wrong to write a program that depended on this exception for its correctness: the fail-fast behavior of iterators should be used only to detect bugs
Example :
Iterators returned by Vector, ArrayList, HashSet , HashMap etc are fail-fast. i.e. most JDK1.4 collections
package in.bibek;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
public class FailFastHashMap
{
public static void main(String[] args)
{
Map countryCode = new HashMap();
countryCode.put("India", "+91");
countryCode.put("UK", "+44");
Iterator iterator = countryCode.keySet().iterator();
while (iterator.hasNext())
{
System.out.println(countryCode.get(iterator.next()));
countryCode.put("USA", "+11");
}
}
}
Output:
+44
Exception in thread "main" java.util.ConcurrentModificationException
at java.util.HashMap$HashIterator.nextEntry(HashMap.java:793)
at java.util.HashMap$KeyIterator.next(HashMap.java:828)
at in.bibek.FailFastHashMap.main(FailFastHashMap.java:21)
Fail Safe :
This iterators doesn’t throw exception if the Collection is modified concurrently. Because these iterators works the clone of the Collection not with the original.
Example : Iterators return by CopyOnWriteArrayList,ConcurrentHashMap (Added in JDK 5)
In the above example if you change HashMap to ConcurrentHashMap things will be fine.
Output :
+44
+91
+11
Leave a Reply