Today I was browsing through some questions on this site and I found a mention of an enum
being used in singleton pattern about purported thread safety benefits
a modern look at an old problem
This approach implements the singleton by taking advantage of Java's guarantee that any enum value is instantiated only once in a Java program and enum provides implicit support for thread safety. Since Java enum values are globally accessible, so it can be used as the singleton.
public enum Singleton {
SINGLETON;
public void method() { }
}
How does this work? Well, the line two of the code may be considered to something like this:
public final static Singleton SINGLETON = new Singleton();
And we get good old early initialized singleton.
Remember that since this is an enum you can always access to instance via Singleton.INSTANCE
as well:
Singleton s = Singleton.INSTANCE;
Advantages
valueOf
method is used with the deserialized name to get the desired instance. Enum
class. The reason that reflection cannot be used to instantiate objects of enum type is because the java specification disallows and that rule is coded in the implementation of the newInstance
method of the Constructor
class, which is usually used for creating objects via reflection:if ((clazz.getModifiers() & Modifier.ENUM) != 0)
throw new IllegalArgumentException("Cannot reflectively create enum objects");
map
. Rather than having a single instance per application (e.g. the java.lang.Runtime
) the multiton pattern instead ensures a single instance per key.Detailed description each of them is too verbose so I just put a link to a good article - All you want to know about Singleton