Free Design patterns lessonsDesign patterns · Stage 0 · Creating objects · Step 1
Singleton
One instance for the whole program: how to write it correctly, why it is controversial, and what to use instead. About 12 minutes.
Which Java implementation of a singleton is inherently safe against thread races, reflection and serialisation?
- AAn enum with a single constant
- BA lazily initialised static field with no synchronisation
- CA public constructor with a static counter
Show the answer
An enum with a single constant. The JVM guarantees one instance, and blocks reflective construction and duplicate deserialisation.
4 questions on this idea
Short questions that apply the idea to new cases: trace it, work out a number, put steps in order. A wrong answer explains itself.
Answer them in your browserFree account, no card. Your progress is saved, and the idea comes back in a quick review later.
Sign up free to solve