2.0 KiB
Singleton Design Pattern — Java Example
Pattern: Creational → Singleton Article: https://ankurm.com/singleton-design-pattern-java/
What this example shows
Six different ways to implement a singleton, compiled and run side by side so their tradeoffs are directly comparable. AppConfigEager initializes at class-load time. AppConfigNaiveLazy defers initialization but is not thread-safe. AppConfigSynchronized fixes thread-safety at the cost of locking on every call. AppConfigDCL uses double-checked locking to avoid that per-call lock. AppConfigHolder uses the initialization-on-demand holder idiom for lazy, thread-safe initialization with no locking at all. AppConfigEnum uses a single-element enum, which the JVM guarantees is a singleton even against reflection and serialization attacks. Main exercises all six in one run.
How to run
javac singleton/*.java -d out/singleton
java -cp out/singleton singleton.Main
Requires Java 25.
Post Section ↔ File Mapping
| Post Section | File(s) |
|---|---|
| Implementation 1 — Eager Initialization | AppConfigEager.java |
| Implementation 2 — Naïve Lazy Initialization | AppConfigNaiveLazy.java |
| Implementation 3 — Synchronized Method | AppConfigSynchronized.java |
| Implementation 4 — Double-Checked Locking | AppConfigDCL.java |
| Implementation 5 — Initialization-on-Demand Holder | AppConfigHolder.java |
| Implementation 6 — Enum Singleton | AppConfigEnum.java |
| Running All Six Implementations Together | Main.java |
Each implementation is renamed to its own class (e.g. AppConfigEager, AppConfigHolder) so all six can be compiled together in one package and compared directly. The "Breaking via Reflection," "Breaking via Serialization," and Spring @Component snippets are illustrative only — they are not part of this repository's runnable example.
Article: https://ankurm.com/singleton-design-pattern-java/ All patterns: https://ankurm.com/design-patterns-java/