ConcurrentSkipListSet - fail-safe or fail-fast iteration using iterator, listIterator, Enumeration and enhanced for loop


ConcurrentSkipListSet -  fail-safe or fail-fast iteration using iterator, listIterator, Enumeration and enhanced for loop.



iterator returned by ConcurrentSkipListSet is fail-safe. Means any structural modification made to ConcurrentSkipListSet like adding or removing elements during Iteration won’t throw any Exception.
import java.util.Collections;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentSkipListSet;
/** Copyright (c), AnkitMittal JavaMadeSoEasy.com */
public class ConcurrentSkipListSetTest {
   public static void main(String args[]) {
          Set<String> concurrentSkipListSet = new ConcurrentSkipListSet<String>();
          concurrentSkipListSet.add("javaMadeSoEasy");
          concurrentSkipListSet.add("ankit");
          System.out.println("-------use iterator-------");
          // fail-safe
          Iterator<String> iterator = concurrentSkipListSet.iterator();
          while (iterator.hasNext()) {
                 concurrentSkipListSet.add("newElement1");
                 System.out.println(iterator.next());
          }
          System.out.println("-------use Enumeration-------");
          // fail-safe
          Enumeration<String> listEnum = Collections
                       .enumeration(concurrentSkipListSet);
          while (listEnum.hasMoreElements()) {
                 concurrentSkipListSet.add("newElement2");
                 System.out.println(listEnum.nextElement());
          }
          System.out.println("-------use enhanced for loop-------");
          // enhanced for loop is fail-safe
          for (String string : concurrentSkipListSet) {
                 concurrentSkipListSet.add("newElement3");
                 System.out.println(string);
          }
   }
}
/*OUTPUT
-------use iterator-------
ankit
javaMadeSoEasy
newElement1
-------use Enumeration-------
ankit
javaMadeSoEasy
newElement1
newElement2
-------use enhanced for loop-------
ankit
javaMadeSoEasy
newElement1
newElement2
newElement3
*/



RELATED LINKS>


ConcurrentSkipListSet - iterate using iterator, listIterator, Enumeration and enhanced for loop



No comments:

Post a Comment