The thread-safety of Enum singletons comes from how Java handles enums internally.
Here’s the magic:
🔧 1. Enum instances are created during class loading
When you declare an enum like this:
public enum Singleton {
INSTANCE;
}
The INSTANCE
is created once when the enum class Singleton
is loaded into memory, and class loading is:
✅ Thread-safe by design (guaranteed by the Java Language Specification).
Only one thread can initialize a class at a time, so multiple threads can’t create multiple enum instances.
🧠 JVM Guarantees for Enum
- Enum constants (
INSTANCE
) are static final fields. - Static initializers are run by the JVM in a synchronized way.
- So even if multiple threads call
Singleton.INSTANCE
simultaneously, the JVM ensures:- The enum class is loaded only once
- The
INSTANCE
is created only once
📦 Behind the Scenes
The enum:
public enum Singleton {
INSTANCE;
}
Is roughly compiled by the JVM into something like:
public final class Singleton extends Enum<Singleton> {
public static final Singleton INSTANCE = new Singleton();
private Singleton() {
super("INSTANCE", 0);
}
}
✅ INSTANCE
is static final
— initialized once, thread-safe.
💡 Enum = Built-in Singleton
JVM handles:
- Thread-safe instantiation ✅
- Serialization ✅
- Reflection attack prevention ✅
You don’t need to write
synchronized
,volatile
, or worry about double-checked locking.
🔐 Summary: Why Enum Singleton is Thread-Safe
Reason | Explanation |
---|---|
Class loading is thread-safe | Only one thread loads the class and creates the instance |
Enum instances are static final | Created once, safely, by JVM |
No custom synchronization needed | JVM takes care of everything |