Read now

How to make perfect Singleton

Singleton pattern is creational design pattern that deals with object creation mechanisms, trying to create objects in a manner suitable to the situation.


The purpose of the Singleton class is to control object creation, limiting the number of objects to only one. Any instance fields of a Singleton will occur only once per class, just like static fields. Singletons are often used where you have to control the resources, such as database connections or sockets.

A perfect Singleton class should be :

  1. Thread safe
  2. Reflection proof


  1. Thread Safe:

If two threads try to initialize your Singleton class at almost the same time then it will create new object of Singleton class. To make it stop to create multiple object of your singleton class we have to make method synchronized.

2. Reflection proof:

Using reflection you can create multiple instance of your Singleton class to make your class reflection proof. To prevent Singleton failure while due to reflection you have to throw a run-time exception in constructor, if the constructor is already initialized and some class to initialize it again.

Now you can make your class a Singleton class that is thread, reflection.

. . .


Add Your Comment

Be the first to comment.

Hire Us!
Brief us about your requirements and we'll get back to you.
Woo! Hooy!
We have just recieved your project brief and our expert will contact you shortly.
Send Again