Java OCA OCP Practice Question 1995

Question

Given the original array,

how many of the following for statements result in an infinite loop at runtime, assuming each is executed independently?.

List<Integer> original = new ArrayList<>(Arrays.asList(1,2,3)); 
  
List<Integer> copy1 = new ArrayList<>(original); 
for(Integer q : copy1) 
   copy1.add(1); //  w  ww  .  java 2 s  . c o m
  
List<Integer> copy2 = new CopyOnWriteArrayList<>(original); 
for(Integer q : copy2) 
   copy2.add(2); 
  
Deque<Integer> copy3 = new ConcurrentLinkedDeque<>(original); 
for(Integer q : copy3) 
   copy3.push(3); 

List<Integer> copy4 = Collections.synchronizedList(original); 
for(Integer q : copy4) 
   copy4.add(4); 
  • A. Zero
  • B. One
  • C. Two
  • D. Three


A.

Note

First of all, the for loops using copy1 and copy4 both throw ConcurrentModificationException at runtime since neither allows modification while they are being iterated upon.

Next, CopyOnWriteArrayList makes a copy of the array every time it is modified, preserving the original list of values the iterator is using, even as the array is modified.

For this reason, the for loop using copy2 completes without throwing an exception or creating an infinite loop.

Finally, the ConcurrentLinkedDeque used in copy3 completes without producing an exception or infinite loop.

The Concurrent collections order read/write access such that access to the class is consistent across all threads and processes, even iterators.

Because the values are inserted at the head of the queue using push() and the underlying data structure is ordered, the new values will not be iterated upon and the loop finishes.

Since none of the for statements produce an infinite loop at runtime, Option A is the correct answer.

If push() had been used instead of offer() in the third loop, with new values being inserted at the tail of the queue instead of at the head, then the for loop would have entered an infinite loop, and Option B would be the correct answer.




PreviousNext

Related