Bird
Raised Fist0

Which design approach best fits this requirement?

easy🔍 Pattern Recognition Q11 of Q15
OOP & Design Patterns - Singleton Pattern - Thread Safety, Double-Checked Locking & Lazy Init
You need to ensure that a class has only one instance throughout the application lifecycle, and this instance must be lazily initialized in a thread-safe manner without incurring synchronization overhead on every access. Which design approach best fits this requirement?
AUse a simple static variable without synchronization and rely on the language's memory model.
BUse a synchronized method that creates the instance on first call, locking every time.
CCreate the instance eagerly at class loading time to avoid synchronization issues.
DImplement double-checked locking with a volatile instance variable to minimize synchronization overhead.
Step-by-Step Solution
  1. Step 1: Understand the problem constraints

    The instance must be lazily initialized and thread-safe, but synchronization overhead should be minimized.
  2. Step 2: Evaluate each approach

    Synchronized method locks on every call, causing overhead. Eager initialization is thread-safe but not lazy. Unsynchronized static variable risks multiple instances in multithreaded contexts. Double-checked locking with volatile ensures lazy init, thread safety, and minimal locking.
  3. Final Answer:

    Option D -> Option D
  4. Quick Check:

    Double-checked locking balances thread safety and performance [OK]
Quick Trick: Double-checked locking minimizes synchronization overhead [OK]
Common Mistakes:
MISTAKES
  • Assuming synchronized method is efficient enough
  • Believing eager initialization is always best
  • Ignoring volatile keyword necessity
Trap Explanation:
PITFALL
  • Synchronized methods are thread-safe but cause performance hits; eager init is thread-safe but not lazy; volatile is essential for double-checked locking correctness.
Interviewer Note:
CONTEXT
  • Tests candidate's understanding of thread-safe lazy initialization tradeoffs.
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