Bird
Raised Fist0

Examine the following Java-like Singleton implementation using double-checked locking:

medium🐞 Bug Identification Q7 of Q15
OOP & Design Patterns - Singleton Pattern - Thread Safety, Double-Checked Locking & Lazy Init
Examine the following Java-like Singleton implementation using double-checked locking:
class Singleton {
  private static Singleton instance;
  public static Singleton getInstance() {
    if (instance == null) {
      synchronized(Singleton.class) {
        if (instance == null) {
          instance = new Singleton();
        }
      }
    }
    return instance;
  }
}
What is the primary issue with this implementation?
AThe getInstance method should be synchronized instead of using double-checked locking.
BThe synchronized block is unnecessary and causes performance degradation.
CThe double null check leads to multiple instances being created.
DThe instance variable is not declared volatile, risking visibility issues.
Step-by-Step Solution
Solution:
  1. Step 1: Understand double-checked locking

    Double-checked locking requires the instance variable to be volatile to prevent instruction reordering.
  2. Step 2: Issue with missing volatile

    Without volatile, other threads may see a partially constructed object due to reordering.
  3. Step 3: Other options

    Synchronized block is necessary for thread safety; double null check prevents multiple instances; synchronizing entire method is less efficient.
  4. Final Answer:

    Option D -> Option D
  5. Quick Check:

    Missing volatile causes subtle thread visibility bugs [OK]
Quick Trick: Volatile needed to prevent partially constructed instance visibility [OK]
Common Mistakes:
MISTAKES
  • Thinking synchronized block is redundant
  • Believing double null check causes multiple instances
  • Assuming method synchronization is better always
Trap Explanation:
PITFALL
  • Missing volatile is subtle and often overlooked, causing thread safety issues.
Interviewer Note:
CONTEXT
  • Tests understanding of Java memory model and double-checked locking correctness.
Master "Singleton Pattern - Thread Safety, Double-Checked Locking & Lazy Init" in OOP & Design Patterns

2 interactive learning modes - each teaches the same concept differently

Want More Practice?

15+ quiz questions · All difficulty levels · Free

Free Signup - Practice All Questions
More OOP & Design Patterns Quizzes