ProgrammingHardProduct-company placement · Java
Which lazily-initialised singleton is thread-safe WITHOUT any explicit synchronization or volatile field?
- A. A static method that checks if (instance == null) and then creates it
- B. A private static nested holder class whose static final field holds the instance
- C. Double-checked locking on a non-volatile static field
- 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
- What is printed? java // static generic method of the main class: static <T extends Comparable<T>> T max(T a, T b) { return a.compareTo(b)…
- What is printed? java class A { private int v = 1; boolean same(A other) { return v == other.v; } void set(A other) { other.v = 9; } } //…
- What is printed? cpp struct M { M(const char s) { cout << s; } }; struct S { M x, y; S() : y("Y"), x("X") { cout << "S"; } }; int main() {…
- What is printed? cpp struct B { virtual ~B() { hi(); } virtual void hi() { cout << "B"; } }; struct D : B { ~D() { cout << "~D "; } void…
- What is printed? cpp struct E { virtual const char what() const { return "E"; } }; struct F : E { const char what() const override {…
- What is printed? cpp struct E { }; struct F : E { }; int main() { try { throw F(); } catch (E&) { cout << "E"; } catch (F&) { cout << "F"…