How to make perfect Singleton

Updated 2 January 2018

Save

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

PURPOSE:

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.

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Start a Project


    Message Sent!

    If you have more details or questions, you can reply to the received confirmation email.

    Back to Home