Java.Multithreading.Why enum singletone is it thread safe ?

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

ReasonExplanation
Class loading is thread-safeOnly one thread loads the class and creates the instance
Enum instances are static finalCreated once, safely, by JVM
No custom synchronization neededJVM takes care of everything
This entry was posted in Без рубрики. Bookmark the permalink.