Java OCA OCP Practice Question 2610

Question

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) The program prints the following: 2 1.
  • b) The program prints the following: 1 2.
  • c) The program prints the following: -1 1 2 3.
  • d) The program prints the following: 2 1 3 -1.
  • e) The program throws a ConcurrentModificationException
  • f) This program results in a compiler error in statement #1


a)

Note

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.




PreviousNext

Related