跪拜 Guibai
← All articles
Android

Singleton in Java and Kotlin: From Eager to Enum, Plus a Thread-Safe ToastManager

By 雨白 ·
Read original on juejin.cn ↗ Google Translate ↗ Alt translation

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.

Summary

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.

Takeaways
— Eager initialization instantiates the singleton at class load time, so a heavy instance can slow startup even if never used.
— Synchronizing the whole getInstance method is slow; double-checked locking restricts synchronization to the first call.
— DCL requires volatile to prevent instruction reordering that could expose an uninitialized object to another thread.
— The static inner class holder idiom achieves lazy initialization without locks, relying on JVM class loading for thread safety.
— Enum singletons prevent both reflection and serialization from creating extra instances, making them the most secure Java option.
— Kotlin's object keyword compiles to an eager singleton with a static INSTANCE field; companion object with by lazy gives lazy initialization.
— Kotlin's by lazy defaults to SynchronizedLazyImpl, which uses double-checked locking underneath.
— The ToastManager uses ApplicationContext to avoid Activity leaks, posts to the main thread, and cancels the previous toast before showing the next.
Conclusions

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.

Concepts & terms
Singleton pattern
A design pattern that ensures a class has exactly one instance and provides a global access point to it. Common implementations include eager, lazy, DCL, static inner class, and enum.
Double-checked locking (DCL)
A technique to reduce locking overhead by checking a condition twice: once without a lock and once inside a synchronized block. It is used to create a single instance lazily while minimizing synchronization cost.
volatile
A Java keyword that prevents instruction reordering and ensures changes to a variable are visible across threads. In the DCL singleton, volatile is needed to avoid exposing a partially constructed object.
Static inner class holder idiom
A way to achieve lazy initialization in Java by placing the singleton instance in a static inner class. The JVM loads the inner class only when getInstance is called, and class loading guarantees thread safety.
Enum singleton
A singleton implemented as a Java enum. Enums are inherently serialization- and reflection-safe because the JVM handles them specially, so no extra code is needed to block those attacks.
ApplicationContext
The global context of an Android application, available for the process's lifetime. Using it in a singleton instead of an Activity context prevents memory leaks because the singleton never holds a reference to an Activity that should be garbage-collected.
From the discussion
Featured comments
booboosui 1 likes

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.

See top comments, translated →
Source: juejin.cn ↗ Google Translate ↗ Backup ↗