CopyOnWriteArraySet - fail-safe or fail-fast iteration using iterator, Enumeration and enhanced for loop program




CopyOnWriteArraySet - fail-safe or fail-fast iteration using iterator, Enumeration and enhanced for loop program.

iterator returned by CopyOnWriteArraySet is fail-safe. Means any structural modification made to CopyOnWriteArraySet 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.CopyOnWriteArraySet;
/**
* Copyright (c), AnkitMittal JavaMadeSoEasy.com
*/
public class CopyOnWriteArraySetTest {
   public static void main(String args[]) {
      Set<String> copyOnWriteArraySet = new CopyOnWriteArraySet<String>();
      copyOnWriteArraySet.add("ankit");
      copyOnWriteArraySet.add("javaMadeSoEasy");
      System.out.println("-------use iterator-------");
      // fail-safe
      Iterator<String> iterator = copyOnWriteArraySet.iterator();
      while (iterator.hasNext()) {
             copyOnWriteArraySet.add("newElement1");
             System.out.println(iterator.next());
      }
      System.out.println("-------use Enumeration-------");
      // fail-safe
      Enumeration<String> listEnum = Collections.enumeration(copyOnWriteArraySet);
      while (listEnum.hasMoreElements()) {
             copyOnWriteArraySet.add("newElement2");
             System.out.println(listEnum.nextElement());
      }
      System.out.println("-------use enhanced for loop-------");
      // enhanced for loop is fail-safe
      for (String string : copyOnWriteArraySet) {
             copyOnWriteArraySet.add("newElement3");
             System.out.println(string);
      }
   }
}
/*OUTPUT
-------use iterator-------
ankit
javaMadeSoEasy
-------use Enumeration-------
ankit
javaMadeSoEasy
newElement1
-------use enhanced for loop-------
ankit
javaMadeSoEasy
newElement1
newElement2
*/



RELATED LINKS>


CopyOnWriteArraySet - iterate using iterator, Enumeration and enhanced for loop program


No comments:

Post a Comment