How would you implement thread safety in a singleton?

First, let’s go over some background on why thread safety may be an issue with singletons. When dealing with singletons, there are two primary ways to initialize the singleton – inside a method using a technique known as lazy loading, or outside a method. Lazy loading is used to save resources by only initializing the singleton when the instance is actually needed. This is what lazy loading could look like for a singleton:

public static Logging getSingleton() {
  /*Create the singleton instance only if it's
    null, which means no one else has created it
    already:
   */
   
   if( singletonInstance  == null ){
      singletonInstance  = new Logging();
   }

   return singletonInstance;
}

Just for reference, this is what the getSingleton() method looks like without lazy loading – note that the singletonInstance is not being initialized:

public static Logging getSingleton() 
{ 
  return singletonInstance; 
}

You can read more about lazy loading in Singletons here: Design Pattern Interview Question 2.

Having the singleton initialized in a method can be a problem

Having the singleton initialized inside a method creates a new problem. What if two or more threads call the method at the same time?

For example, let’s say that a thread – let’s call it thread A – switches out immediately after checking to see if the singleton instance is NULL. Now, let’s say that another thread – call it thread B – gets switched into the method call and actually completes the execution of the getInstance() method. This means that thread B will actually retrieve and construct an instance of the singleton. But, thread A will get switched back into the method and then create another instance of the singleton! So, now we have two singleton instances, when the whole point of a singleton is to only allow one instance to be created.

Make the singleton thread safe is the solution

This is clearly a problem, but there is a solution. That solution is to make the method thread safe. How do we make a method thread safe? Well, it’s pretty simple actually – we just add the synchronized keyword to the method signature to make it thread safe. So, this is what the method ends up looking like:

// Return the singleton instance.
     public synchronized static Logger getInstance() {
         if( instance == null ){
             instance = new Logger();
         }

         return instance;
     }

How does the synchronized keyword make a method thread safe?

Adding the synchronized keyword to the method signature basically prevents more than one thread from entering the method at a given time. So, one thread must run the method to completion before another thread can even enter the method. This will of course prevent multiple singletons from being created because once the first singleton is created, any subsequent calls to the getInstance method will just return the one instance that has already been created. And that is what thread safety is all about.

Hiring? Job Hunting? Post a JOB or your RESUME on our JOB BOARD >>

Subscribe to our newsletter for more free interview questions.

2 thoughts on “Thread Safety in Singleton”

WordPress › Error

There has been a critical error on your website.

Learn more about debugging in WordPress.