Bird
Raised Fist0

Consider the following Python code implementing a thread-safe Singleton with double-checked locking. What will be the output of the print statement?

easy🧾 Code Trace Q3 of Q15
OOP & Design Patterns - Singleton Pattern - Thread Safety, Double-Checked Locking & Lazy Init
Consider the following Python code implementing a thread-safe Singleton with double-checked locking. What will be the output of the print statement?
ATrue
BFalse
CRaises RuntimeError
DNone
Step-by-Step Solution
Solution:
  1. Step 1: Trace instance creation for s1

    _instance is None, lock acquired, instance created and assigned.
  2. Step 2: Trace instance creation for s2

    _instance is not None, returns existing instance.
  3. Final Answer:

    Option A -> Option A
  4. Quick Check:

    s1 and s2 refer to the same Singleton instance [OK]
Quick Trick: Double-checked locking returns same instance after first creation [OK]
Common Mistakes:
MISTAKES
  • Ignoring double-checked locking causes multiple instances
Trap Explanation:
PITFALL
  • Candidates may think second call creates new instance without checking _instance first.
Interviewer Note:
CONTEXT
  • Tests ability to trace thread-safe lazy singleton code
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