AlgoViz

Singleton

medium 60 min

One 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

StepThread AThread Binstancebuilds
1first check: emptynull0
2first check: emptynull0
3waitstakes the locknull0
4waitssecond check: empty, buildsnull1
5waitsstores, leaves the lockconfig1
6takes the lock, second check: setconfig1
7returns configreturned configconfig1
Cover the second check in step 6 with your hand: A builds again, and builds becomes 2.

Test list

TestHowCatches
Identityget() is get()A door that always builds
Count under loadBarrier, 8 threads, builds == 1A missing lock or second check
Closed constructorDirect construction must failAn accidental second object
Copy and pickleCopy must be the same object, loading must not change itThe back doors
Failure, then successFirst build raises, second worksA half-set field
OrderRun tests shuffledState that leaks