Implementing Singleton with an Enum (in Java)
I have read that it is possible to implement Singleton
in Java using an Enum
such as:
public enum MySingleton {
INSTANCE;
}
But, how does the above work? Specifically, an Object
has to be instantiated. Here, how is MySingleton
being instantiated? Who is doing new MySingleton()
?
Solution 1:
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
Here
INSTANCE
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.
Solution 2:
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).