Implementing Singleton with an Enum (in Java) Implementing Singleton with an Enum (in Java) java java

Implementing Singleton with an Enum (in Java)


This,

public enum MySingleton {  INSTANCE;   }

has an implicit empty constructor. Make it explicit instead,

public enum MySingleton {    INSTANCE;    private MySingleton() {        System.out.println("Here");    }}

If you then added another class with a main() method like

public static void main(String[] args) {    System.out.println(MySingleton.INSTANCE);}

You would see

HereINSTANCE

enum fields are compile time constants, but they are instances of their enum type. And, they're constructed when the enum type is referenced for the first time.


An enum type is a special type of class.

Your enum will actually be compiled to something like

public final class MySingleton {    public final static MySingleton INSTANCE = new MySingleton();    private MySingleton(){} }

When your code first accesses INSTANCE, the class MySingleton will be loaded and initialized by the JVM. This process initializes the static field above once (lazily).


In this Java best practices book by Joshua Bloch, you can find explained why you should enforce the Singleton property with a private constructor or an Enum type. The chapter is quite long, so keeping it summarized:

Making a class a Singleton can make it difficult to test its clients, as it’s impossible to substitute a mock implementation for a singleton unless it implements an interface that serves as its type.Recommended approach is implement Singletons by simply make an enum type with one element:

// Enum singleton - the preferred approachpublic enum Elvis {INSTANCE;public void leaveTheBuilding() { ... }}

This approach is functionally equivalent to the public field approach, except that itis more concise, provides the serialization machinery for free, and provides anironclad guarantee against multiple instantiation, even in the face of sophisticatedserialization or reflection attacks.

While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.