ProgrammingHardProduct-company placement · Java

Which lazily-initialised singleton is thread-safe WITHOUT any explicit synchronization or volatile field?

  1. A. A static method that checks if (instance == null) and then creates it
  2. B. A private static nested holder class whose static final field holds the instance
  3. C. Double-checked locking on a non-volatile static field
  4. D. A public static non-final field assigned in the constructor

Correct answer: B. A private static nested holder class whose static final field holds the instance

The holder class is initialised only when getInstance() first touches it, and class initialisation is guaranteed thread-safe by the JVM. A plain null check races, and double-checked locking needs volatile.

More OOP with C++ and Java questions

Exams that ask this topic