Singleton
medium 60 minOne object and one way to reach it.
Watch lesson4:52
Verify
Trace it by hand, then test identity, count, threads and order.
The point: check four things: the same object, built once, complete when seen, and no test that depends on another.
Trace
Two threads, step by step
| Step | Thread A | Thread B | instance | builds |
|---|---|---|---|---|
| 1 | first check: empty | null | 0 | |
| 2 | first check: empty | null | 0 | |
| 3 | waits | takes the lock | null | 0 |
| 4 | waits | second check: empty, builds | null | 1 |
| 5 | waits | stores, leaves the lock | config | 1 |
| 6 | takes the lock, second check: set | config | 1 | |
| 7 | returns config | returned config | config | 1 |
Test list
| Test | How | Catches |
|---|---|---|
| Identity | get() is get() | A door that always builds |
| Count under load | Barrier, 8 threads, builds == 1 | A missing lock or second check |
| Closed constructor | Direct construction must fail | An accidental second object |
| Copy and pickle | Copy must be the same object, loading must not change it | The back doors |
| Failure, then success | First build raises, second works | A half-set field |
| Order | Run tests shuffled | State that leaks |