ConcurrentHashMap program to show Iterator is fail-safe in java


ConcurrentHashMap - Iterator on keySet, values and  entrySet is  fail-safe or fail-fast?

The iterators returned by the iterator() method of the collections returned by all three Map's “collection view methods" are fail-safe. Means any structural modification made to ConcurrentHashMap like adding or removing elements during Iteration won’t throw any Exception.



HashMap and ConcurrentHashMap - Similarity and Differences


HashMap vs Hashtable vs LinkedHashMap vs TreeMap - Differences


Map hierarchy in java - Detailed - HashMap, Hashtable, ConcurrentHashMap, LinkedHashMap, TreeMap, ConcurrentSkipListMap, IdentityHashMap, WeakHashMap, EnumMap classes


import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ConcurrentHashMapFailFastExample {
public static void main(String args[]){
  
   Map<Integer,String> concurrentHashMap=new ConcurrentHashMap<Integer,String>();
   concurrentHashMap.put(11, "ankit");
   concurrentHashMap.put(21, "javaMadeSoEasy");
  
   System.out.println("\n---1. Iterate on keys, by obtaining iterator on keySet---");
   //fail-fast
   Iterator<Integer> keyIterator=concurrentHashMap.keySet().iterator();
   while(keyIterator.hasNext()){
          concurrentHashMap.put(4,"newEle1");//unComment to avoid ConcurrentModificationException
          System.out.println(keyIterator.next());
   }
  
   System.out.println("\n---2. Iterate on values, by obtaining iterator on values---");
   //fail-fast
   Iterator<String> valueIterator=concurrentHashMap.values().iterator();  
   while(valueIterator.hasNext()){
          concurrentHashMap.put(4,"newEle1");//unComment to avoid ConcurrentModificationException
          System.out.println(valueIterator.next());
   }
   System.out.println("\n---3. Iterate on entry, by obtaining iterator on entrySet---");
   //fail-fast
   Iterator<Entry<Integer, String>> entryIterator=concurrentHashMap.entrySet().iterator();
   while(entryIterator.hasNext()){
          concurrentHashMap.put(4,"newEle1");//unComment to avoid ConcurrentModificationException
          System.out.println(entryIterator.next());
   }
}
}
/*OUTPUT
---1. Iterate on keys, by obtaining iterator on keySet---
21
11
---2. Iterate on values, by obtaining iterator on values---
newEle1
javaMadeSoEasy
ankit
---3. Iterate on entry, by obtaining iterator on entrySet---
4=newEle1
21=javaMadeSoEasy
11=ankit
*/


RELATED LINKS>


HashMap - Iterate on keys by obtaining keySet, Iterate on values by obtaining values, Iterate on entry by obtaining entrySet


HashMap - synchronizing map using Collections.synchronizedMap




ArrayList - add, add element at specific index methods program


Labels: Core Java
eEdit
Must read for you :