Singleton Design Pattern

Rikam Palkar
Level Up Coding
Published in
3 min readFeb 17, 2022

--

Photo by call me hangry 🇫🇷 on Unsplash

Why do we even need a singleton pattern? Consider a situation where you only want to create one instance of the class. For example, let’s say you’re calling an API in your project, as every API’s first step is to authenticate the client. After successful authentication, the server generates a session, which is alive for some time.

Imagine for every single request you’re creating a session, which is wrong at so many levels. For example, One Facebook’s login to logout is one session. Now if you like one post, your session will expire and you’ll have to login again. If you add one post again you will create a new session which will log you out of the system.

You should only create a session for all other requests. Once you login, you can do many likes, comments and posts without closing the session.

This is where we can use the singleton pattern.

Listing 1: Following code snippet is how you can implement a single pattern in C#.

As you see in listing 1, we have a static Initialise() method, so whenever your project calls this method for the first time, it creates a new object then later it will just return the same instance.

There’s one major problem with the above code, as it’s not thread-safe. It creates an instance for every thread that makes a request.

It’s ok, no need to panic, as we have a solution for such cases. We have 2 keywords to help us out:

Volatile and Synchronized

Volatile (in brief):

In a multithreaded scenario, a Thread which is currently accessing the CPU can cache some resources such as properties, variables etc. Resources are stored in the CPU’s cache memory for faster processing. And while it has it, thread can modify the values of these variables.

Now the problem is other threads are still having access to the old values which are on RAM. Here we have a mismatch issue, so in order to avoid that we use volatile keywords. It makes sure cache data is updated on RAM and vice-versa.

So if a resource is being modified by multiple threads that are executing at the same time they all can still have updated values.

Listing 2: Thread safe singleton’s implementation.

In Java we have synchronized keyword to take the pain away.

Synchronized (in brief):

Synchronization allows only one thread to access the resource at a time. No other thread can get access to that resource until the assigned thread finishes its task. Threads execute asynchronously. Synchronization helps us by making threads synchronized w.r.t. resources.

We can use a locking mechanism to make it thread-safe.

Listing 3: Singleton’s implementation in Java.

Catch me on Linkedin !!

--

--