Bird
Raised Fist0

Identify the bug in the following singleton implementation that aims to use lazy initialization with double-checked locking in Java-like pseudocode:

medium🐞 Bug Identification Q14 of Q15
OOP & Design Patterns - Singleton Pattern - Thread Safety, Double-Checked Locking & Lazy Init
Identify the bug in the following singleton implementation that aims to use lazy initialization with double-checked locking in Java-like pseudocode:
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 subtle bug that can cause thread-safety issues?
AThe synchronized block is too large, causing unnecessary locking overhead.
BThe instance variable is not declared volatile, risking instruction reordering.
CThe first null check outside synchronized block is redundant and should be removed.
DThe constructor is not private, allowing multiple instances externally.
Step-by-Step Solution
  1. Step 1: Analyze double-checked locking correctness

    Without volatile, the instance reference may be visible before full construction due to instruction reordering.
  2. Step 2: Check other options

    Synchronized block size is minimal and correct; first null check is necessary for performance; constructor privacy is unrelated to this snippet.
  3. Final Answer:

    Option B -> Option B
  4. Quick Check:

    Missing volatile causes subtle thread-safety bugs [OK]
Quick Trick: Volatile prevents instruction reordering in double-checked locking [OK]
Common Mistakes:
MISTAKES
  • Ignoring volatile keyword necessity
  • Thinking synchronized block size is the bug
  • Assuming constructor privacy is the main issue here
Trap Explanation:
PITFALL
  • Many overlook volatile, assuming synchronized alone suffices for thread safety.
Interviewer Note:
CONTEXT
  • Tests deep knowledge of Java memory model and double-checked locking pitfalls.
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