Java OCA OCP Practice Question 2639

Question

What changes need to be made to make the following singleton pattern correct?

Choose all that apply.

public class Main { 
   public static Main instance; 
   private Main() {} 
   public static Main getMain() { 
      if(instance == null) { 
         instance = new Main(); 
      } /*from  w ww . j a v  a  2  s.  c  o m*/
      return instance; 
   } 
} 
  • A. None; the singleton pattern is properly implemented.
  • B. Rename instance to instance.
  • C. Rename getMain() to getInstance().
  • D. Change the access modifier of instance from public to private.
  • E. Mark instance final.
  • F. Add synchronized to getMain().


D, F.

Note

A is incorrect, as there are definitely some problems with the singleton implementation.

B and C are incorrect, as naming of the instance variable and access method are not required as part of the pattern.

The public modifier on the instance instance means that any class can access or even replace the instance, which breaks the singleton pattern; hence D is required to fix the implementation.

E is incorrect, as marking the instance final would prevent lazy instantiation and as the code would not compile.

F is also required, since without this step two threads could create two distinct instances of the singleton at the same time, which would violate the singleton pattern.




PreviousNext

Related