Consider the following program:
import java.util.*; import java.util.concurrent.*; class Main {// w w w . ja va 2s.c o m public static void main(String []args) { Set<String> set = new CopyOnWriteArraySet<String>(); // #1 set.add("2"); set.add("1"); Iterator<String> iter = set.iterator(); set.add("3"); set.add("-1"); while(iter.hasNext()) { System.out.print(iter.next() + " "); } } }
Which one of the following options correctly describes the behavior of this program?
a)
Since the iterator was created using the snap-shot instance when the elements "2" and "1" were added, the program prints 2 and 1.
Note that the CopyOnWriteArraySet does not store the elements in a sorted order.
Further, modifying non-thread-safe containers such as TreeSet using methods such as add()
and using the older iterator will throw a ConcurrentModificationException.
However, CopyOnWriteArraySet is thread-safe and is meant to be used concurrently by multiple threads, and thus does not throw this exception.