Best way of using singleton class

SAURABH OMER
4 min readJun 27, 2022

--

SO the design pattern is very important for developer . Singleton pattern is very common and useful .

Why create singleton class :

This is used to control multiple object of a class and it has only one point to create instance. Singletons are often useful where you have to control the resources, such as database connections or sockets.

It is seems to be very easy but if we will go for implementation , A lots of confusion will come on mine .

How to create a singleton class :

There are two way to initialize any singleton object.

1. Eager initialization:

In this initialization , The instance is created at the time of class loading . making the Constructor as private so new object can’t be created from other class and also maintain a single point to create object.

public class AppDatabase {

private static volatile AppDatabase instance = new AppDatabase();

//private constructor .

private AppDatabase(){}

public static AppDatabase getInstance() {

return instance;

}

}

In this approach there is a major drawback. This instance is created at the time of class loading But what if not required instance. so this may leads to memory leaks. To resolve this problem we will use Lazy Initialization method.

2. Lazy Initialization method :

In this type of initiazation , getInstance() will check if there is any instance of that class is already created? if yes then return that one if not then create a new instance of the singleton class and returns that instance.

public class AppDatabase {

private static volatile AppDatabase instance = null;

//private constructor .

private AppDatabase(){}

public static AppDatabase getInstance() {

if (instance == null){

//if there is no instance available… create new one

instance = new AppDatabase();

}

return instance;

}

. So, that means above code will make the perfect Singleton. Right???? No.

https://paypal.me/saurabhomer1?locale.x=en_GB
https://paypal.me/saurabhomer1?locale.x=en_GB

In above Singleton class, by using Java Reflection API you can create more than one instance.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.

public class AppDatabase

{

private static AppDatabase instance;

//private constructor.

private AppDatabase(){

//Prevent form the reflection api.

if (instance != null)

{

throw new RuntimeException(“Use getInstance() method to get the single instance of this class.”);

}

}

public static AppDatabase getInstance()

{

if (instance == null)

{

//if there is no instance available… create new one

instance = new AppDatabase();

}

return instance;

}

}

Make Singleton thread safe:

If two threads try to initialize the Singleton class at almost the same time.Two threads are created almost simultaneously and they are calling getInstance().so We will use getInstance() method as synchronized.

public class AppDatabase

{

private static AppDatabase instance;

//private constructor.

private AppDatabase(){

//Prevent form the reflection api.

if (instance != null)

{

throw new RuntimeException(“Use getInstance() method to get the single instance of this class.”);

}

}

public synchronized static AppDatabase getInstance()

{

if (instance == null)

{

//if there is no instance available… create new one

instance = new AppDatabase();

}

return instance;

}

}

As you made your getInstance() class synchronized the second thread will have to wait until the getInstance() method is completed for the first thread. This way we can achieve thread safety.but this is unnecessary synchronization that is not required once the instance variable is initialized.

Double check locking:

In this, you will make the Singleton class in the synchronized block if the instance is null. So, the synchronized block will be executed only when the sSoleInstance is null and prevent unnecessary synchronization once the instance variable is initialized. and don’t forget make instance variable as volatile. Without volatile modifier, it’s possible for another thread in Java to see half initialized state of instance variable, but with volatile variable guaranteeing happens-before relationship, all the write will happen on volatile sSoleInstance before any read of sSoleInstance variable.

public class AppDatabase

{

private static volatile AppDatabase instance;

//private constructor.

private AppDatabase(){

//Prevent form the reflection api.

if (instance != null)

{

throw new RuntimeException(“Use getInstance() method to get the single instance of this class.”);

}

}

public synchronized static AppDatabase getInstance()

{

//Double check locking pattern

if (instance == null)

{

//Check for the first time synchronized

(AppDatabase.class) {

//Check for the second time.

//if there is no instance available… create new one

if (instance == null)

instance = new AppDatabase();

}

}

return instance;

}

}

Now, above Singleton class is thread safe. Making Singleton thread safe is especially required in multi-threaded application environment like in Android Applications.

Cheers.

--

--

SAURABH OMER

Passionate Android Developer from NIT Durgapur, dedicated to crafting innovative and user-centric mobile experiences.