Singleton in Java and Kotlin: From Eager to Enum, Plus a Thread-Safe ToastManager
A half-built object from a misordered DCL is a classic production bug, and holding an Activity in a singleton leaks memory. The implementations here give JVM and Android developers a reference for thread-safe, lazy singletons, and the ToastManager shows exactly how to handle threading and context properly.
Design patterns are proven solutions to common problems, and the singleton is among the most frequently used. The article walks through five Java implementations: eager initialization, lazy with synchronized, double-checked locking (DCL) with volatile, static inner class holder, and enum. Eager is simple and thread-safe but creates the instance at class load time even if never used. Lazy and DCL trade complexity for on-demand creation, with volatile preventing the instruction reordering that can expose a half-built object. The static inner class offers lazy loading with no lock overhead, while the enum is the only variant that blocks both reflection and serialization attacks.
Kotlin simplifies the pattern with the object keyword, which compiles to an eager singleton with a static INSTANCE field. Pairing companion object with by lazy yields a lazy singleton, backed by SynchronizedLazyImpl, which uses double-checked locking under the hood.
The article closes with a real Android ToastManager: a DCL singleton that holds an application context to avoid memory leaks, switches to the main thread from any caller, and cancels the previous toast before showing a new one. The code handles repeated taps and background-thread calls cleanly.
The enum singleton's reflection and serialization protections are rarely needed in practice, but they come at no extra cost, so they make the enum the safest default for JVM singletons.
Kotlin's object hides the eager initialization, and without decompiling the bytecode, developers may not realize the instance exists even before first use, which can be a performance trap for heavy objects.
Next to DCL, there's another pitfall that's easier to trip on: top-level val is initialized in file order, not dependency order. What I stepped on was writing the singleton object in the upper part of the file and the config constants below; compilation passes all the way, but at runtime the object reads an empty string for the constant. This has nothing to do with volatile; it's an ordering issue: file-level vals compile into static fields, assigned in declaration order, so anything running earlier only sees the default value of something declared later, and the compiler stays quiet. The verification method is crude: move the entire constants section before the object; if behavior changes, that's it.