Design PatternsL3 · Medium
Singleton Pattern: Thread-Safe Config Manager
Problem
Design an AppConfig singleton that loads configuration from environment/file once and provides global read access. Understand WHY naive singletons break in multithreaded environments and implement a thread-safe version.
Requirements
- AppConfig.getInstance() always returns the same instance
- Config loaded once at first getInstance() call (lazy initialization)
- Config is read-only after loading: get(key), getInt(key), getBool(key)
- AppConfig.reload() — only for testing/hot reload, protected by lock
- Show the race condition in a naive singleton (no locks)
- Fix with double-checked locking or initialization-on-demand pattern
Constraints
- –No public constructor
- –getInstance() must be safe to call from multiple threads simultaneously
✓ Saved