Question Bank
/

Design Patterns Walk-Through

Design Patterns Walk-Through

Hard drills on Singleton, Strategy, Observer, and Decorator. Concrete Java implementations to read, critique, and extend, plus one thread-safety twist.

Question Bank
Hard
Java
design-patterns
oop
singleton
interview-prep

254 views

2

Critique the lazy Singleton below. Identify the thread-safety bug and rewrite it using the holder idiom.

Examples

Example 1:

Input: two threads racing the lazy null check on Config.get()
Output (buggy version): both threads pass the null check and instantiate two distinct Config objects
Output (fixed version with holder idiom): exactly one Config instance across all callers
Explanation: JVM guarantees a nested static class loads lazily and exactly once, so the holder idiom is thread-safe without explicit locking. Even cleaner: enum Config { INSTANCE; } because the JVM serializes enum instantiation.

4 more questions, with full solutions and explanations, are available for premium members.

Upgrade to Premium