I am not able to understand how Enum can be used for thread safe singleton instantiation.
So let us say I have a class A which I want to make singleton. How do I do that using Enum ? I came across suggestion like the code below, but not really able to understand. In the below shall I replace INSTANCE with A singleObj = new A();
?
Moreover, how exactly should class A look like as in what thing should I take care of there .. for example: making constructor private etc.
public enum EasySingleton{
INSTANCE;
}
In the below shall I replace INSTANCE with
A singleObj = new A();
?
You don't. You use:
EasySingleton instance = EasySingleton.INSTANCE;
You write the singleton just like a normal class, with whatever methods you want etc - but no public constructors (which aren't valid in enums anyway).
See more on this question at Stackoverflow