Singleton Class in Java
I guess everyone is aware of what singleton class does? If not, then let me explain — Singleton class is responsible to let you create a single object of it’s own, only one object.
So, how’s it possible that you can create a single object only from that class?
Well, you can do that by making a private constructor. But still if we make a private constructor then I can not do ‘new SingletonClass()’ from outside of the class, so how can I create a single object even?
Fair question. isn’t ???
There are multiple ways to create singleton class? So, let’s go through one by one. First one: Lazy initialisation
But in above lazy initialisation there is an issue, can anyone guess?
Above solution can not give you 100% guarantee that, it will create only one object. Think of multithreading — Suppose there are two threads and simultaneously both thread trying to get singleton object?

So what is the solution?
Let’s make synchronised getSingletonObject() method.
But, still don’t you think, synchronisation is expensive?
Fair question, isn’t???
Good point, and it’s actually a little worse than you make out: the only time synchronization is relevant is the first time through this method. In other words, once, we have set the ‘singletonObject’ variable to instance of SingletonPatternExample, we have no further need to synchronized this method. After the first time though, synchronization is totally unneeded overhead.
So, what is the other solution?
“Move to an eagerly created instance rather than lazily created one.”
If your application always creates and uses an instance of the Singleton or the overhead pf creation and runtime aspects of the Singleton are not onerous, you may want to create your Singleton eagerly, like above. Using above approach, we rely on JVM to create the unique instance of the Singleton, when the class is loaded. The JVM guarantees that the instance will be created before any thread accesses the static singletonObject variable.
There is one more way to write Singleton class!
“Double Checked Locking”
The volatile keyword ensures that multiple threads handle the singletonObject variable correctly when it is being initialized to the Singleton class.
If performance is an issue in your case, then this method can drastically reduce the overhead.
That’s all for a Singleton class. Please find different way to crack this single object creation behaviour in above method.