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.
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
Iterators returned by Vector, ArrayList, HashSet , HashMap etc are fail-fast. i.e. most JDK1.4 collections
public class FailFastHashMap
public static void main(String args)
Map<String,String> countryCode = new HashMap<String,String>();
Iterator<String> iterator = countryCode.keySet().iterator();
Exception in thread "main" java.util.ConcurrentModificationException
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.