Singleton
medium 60 minOne object and one way to reach it.
Watch lesson4:52
Problem
Copies that drift, and what exactly must be guaranteed.
The point: say what must be one, and one per what, before you write a static field.
The task
What we are asked
The first minute
Interviewer
Our program has an auth part, a payment part and an analytics part. They all need the configuration. Design the configuration manager.
You
Is this one process with three parts, or three services in three processes?
Interviewer
Good question. One process.
You
Then one object in memory is enough. I will guarantee that it is built once, also with many threads, and that readers always see complete values. If they were separate services, each process would have its own object, and I would need a shared source and a way to announce changes.
From words to guarantees
| Requirement | Guarantee | How |
|---|---|---|
| All parts decide by the same values | One object | Private constructor, one door |
| Reading the file is slow | Built at most once | Lazy with a lock, or eager |
| Eight request threads | No two builders, no half-built object | Second check, safe publication |
| Operations may move the database | Later readers see the new address | Volatile or locked field |
| Unknown key | Loud error | Exception with the name |
The design that hurts: one each
1/3Each part is independent
That sounds good, and for most things it is.
owns (dies together)