Java OCA OCP Practice Question 1989

Question

Which statement about the following class is correct?.

package mypkg; /*  w  w  w  .ja v a 2 s . c om*/
import java.util.*; 
public class Main { 
   private List<Integer> data = new ArrayList<>(); 
   public synchronized void addValue(int value) { 
      data.add(value); 
   } 
   public int getValue(int index) { 
      return data.get(index); 
   } 
   public int size() { 
      synchronized(Main.class) { 
         return data.size(); 
      } 
   } 
} 
  • A. The code does not compile because of the size() method.
  • B. The code compiles and is thread-safe.
  • C. The code compiles and is not thread-safe.
  • D. The code does not compile for another reason.


C.

Note

The class compiles without issue, making Options A and D incorrect.

The class attempts to create a synchronized version of a List<Integer>.

The size() and addValue() help synchronize the read/write operations.

The getValue() method is not synchronized so the class is not thread-safe, and Option C is the correct answer.

It is possible that one thread could add to the data object while another thread is reading from the object, leading to an unexpected result.

The synchronization of the size() method is valid, but since Main.

class is a shared object, this will synchronize all instances of the class to the same object.

This could result in a substantial performance cost if enough threads are creating Main objects.




PreviousNext

Related