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


ConcurrentSkipListMap -  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 ConcurrentSkipListMap like adding or removing elements during Iteration won’t throw any Exception.


import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentSkipListMap;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ConcurrentSkipListMapTest {
public static void main(String args[]){
  
   Map<Integer,String> concurrentSkipListMap=new ConcurrentSkipListMap<Integer,String>();
   concurrentSkipListMap.put(11, "ankit");
   concurrentSkipListMap.put(21, "javaMadeSoEasy");
  
   System.out.println("\n---1. Iterate on keys, by obtaining iterator on keySet---");
   //fail-safe
   Iterator<Integer> keyIterator=concurrentSkipListMap.keySet().iterator();
   while(keyIterator.hasNext()){
          concurrentSkipListMap.put(4,"newEle4");
          System.out.println(keyIterator.next());
   }
  
   System.out.println("\n---2. Iterate on values, by obtaining iterator on values---");
   //fail-safe
   Iterator<String> valueIterator=concurrentSkipListMap.values().iterator();
   while(valueIterator.hasNext()){
          concurrentSkipListMap.put(5,"newEle5");
          System.out.println(valueIterator.next());
   }
   System.out.println("\n---3. Iterate on entry, by obtaining iterator on entrySet---");
   //fail-safe
   Iterator<Entry<Integer, String>> entryIterator=concurrentSkipListMap.entrySet().iterator();   
   while(entryIterator.hasNext()){
          concurrentSkipListMap.put(6,"newEle6");
          System.out.println(entryIterator.next());
   }
}
}
/*OUTPUT
---1. Iterate on keys, by obtaining iterator on keySet---
11
21
---2. Iterate on values, by obtaining iterator on values---
newEle4
newEle5
ankit
javaMadeSoEasy
---3. Iterate on entry, by obtaining iterator on entrySet---
4=newEle4
5=newEle5
6=newEle6
11=ankit
21=javaMadeSoEasy
*/



RELATED LINKS>

Program to use ConcurrentHashMap’s putIfAbsent method


Program to sort Employee list on basis of name in ascending order by implementing Comparable interface and overriding its compareTo method


eEdit
Must read for you :