Singleton Design Pattern

Rasika Weragoda
5 min readApr 17, 2020

I hope you guys read my introduction article of design pattern in java. If not then the link is available here Design Pattern in Java. This article does not totally depend on the previous article (Design Pattern in Java). But it has some basic understanding of the background of design patterns. Just remember the Singleton design pattern belongs to the category of creational design pattern

This is the most widely used design pattern in the java world because it is very easy to implement and it solves lots of real-world problems. This design pattern guarantees:

  1. only one instance is created: static nature
  2. control of resources: object instantiated is controlled by the implementation
  3. lazily loaded: instantiate the object when needed

The use cases of this design pattern are:

  • runtime environment
  • logger
  • Spring beans (spring boot framework)

Enough taking right, Let’s have some coding😁😁😁

So as I mentioned above, the runtime environment used in the singleton design pattern. which means Runtime object’s instance is created only one time 🤔. Alright let’s check it out

check java runtime environment is a singleton design pattern

So what you think if 2 instances of Runtime objects are same then we have output as “same instance!!!”. If really Runtime object uses the singleton design pattern this should be printed. Let’s look at the output.

output

Hell yeah, 😍 two instances of the Runtime object are same. So it used the concept of Singleton.

Let’s look at how to create a singleton object

In this part, we look at how to create the singleton object that is able to access the database.

note:- just remember, although singleton object has static nature, it is not implementing the static class, Because singleton object needs to tread safely and static class is not guaranteed that. it has a private instance, constructor and no parameters in the constructor.

At first, we created a DB singleton object with no lazily loaded and no thread-safe.

singleton DB class

Above code demo, we have a private instance (control of resources) and we have a private constructor with no parameter. since it is private users cannot create new DB instance as we want. Finally, we have getDB() static method to get the private static instance. calling this method user can get the singleton DB object.

Now we need to check DB object is singleton or not

Test class

Same as Runtime example, we create 2 instances of DB object and check they are the same instance or not. if there are the same instance then we used the singleton design pattern.

the output of Test object

😍 lovely we get same object output as Runtime example. Now we know we create the DB class with singleton design pattern.

😫 wait a minute, what about lazily loaded concept ??? we did not apply that concept to DB class. Even though it satisfied

1 one instance

2 control of resources

it does not satisfy the lazily loaded concept. now we have eagerly loaded instance. Let’s convert it to a lazily loaded instance

note:-
private static DB dbinstance = new DB();
this line create a DB instance where we use it or not that is why it is called eagerly loaded
DB class lazily loaded

well, The difference is only we check the DB instance is null then only we created the object. Because we already know that singleton Object only creat one instance. Using lazily loaded may improve the performance of your application.

Now everything is fine, we almost have done 🤗. But one thing that we need to fix, which is we need to make this singleton DB object as thread-safe(multiple threads can be able to access the object same time).

DB class is thread-safe code

I know you must be confused by looking at this code snippet 😶. No worries I will explain each one at a time🤗

Alright, you can see we add the keyword volatile in DB instance. What the heck is that ??? we know Java compiler creates lots of cache value to speed up the process right. So by applying a volatile variable(DB instance), we say to java compiler and thread do not cache value this variable and must-read on from main memory. So this ensures that this object remains singleton any of the changes in JVM. Cool right 😁

So why you having throw exception in constructor class ??? It is private and it cannot be instantiated by anyone 🤔 what is the point here ??? Alright, it is actually cannot be instantiated by anyone I accept that, But Reflection API can be accessed at run time and also it can modify the class to speed up the process. That is why we say to the constructor if there is an existing DB instance, we don't need anymore. Because we use the singleton design pattern right. So we protected this object of being reflected. 🤩

I know you might think there are lots of things happen under the hood right. Of course, it is. Now will understand what happened to the getDB() method. Here we check DB instance is null right. If it null then we allow entering the synchronized block. Inside the synchronized block, can only be executed a single thread at a time. Suppose DB instance is null and 2 threads are trying to add on it. Then synchronized and check null again and if another class lock on that then it will block our code and return the synchronize lock to our code. That is why we double-check the DB install is null.

I hope you guys understand the singleton design pattern ✌

--

--