How do you write a Thread-Safe Singleton?

John Kroubalkian

I have written plenty of non-thread-safe Singletons but it wasn't until recently when I tracked it down that I realized that thread-safety could be a big problem.

The problem is that in the typical Singleton implementation (at least the ones I've seen) there is the ability to create multiple versions of the single instance...I know, "But How?".

Well, in the getInstance() call the instance is checked for null, and then immediately constructed if it is null, and then the instance is returned.

The problem is that the thread (Ta) making the call could swap-out immediately after checking for a null. A subsequent thread (Tb) could then make a call to get the instance and construct an instance of the Singleton. When the original thread (Ta) is then swapped back in, it would construct and return a completely separate object. BAD KITTY!

The following code snippet shows an example of a thread-safe Singleton.

package com.jgk.patterns.singleton;

public class JGKSingleton {
  
  /* Here is the instance of the Singleton */
  private static JGKSingleton instance_;

  /* Need the following object to synchronize */
  /* a block */
  private static Object syncObject_;

  /* Prevent direct access to the constructor
  private JGKSingleton() {
    super();
  }


  public static JGKSingleton getInstance() {

    /* in a non-thread-safe version of a Singleton   */
    /* the following line could be executed, and the */ 
    /* thread could be immediately swapped out */
    if (instance_ == null) {

      synchronized(syncObject_) {

        if (instance_ == null) {
           instance_ = new JGKSingleton();
        }

      }

    }
    return instance_;
  }
}
NOTE: The 2nd check for if (instance_ == null) is needed to avoid making another unnecessary construct.

Don't let this byte you! ;-)

Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

About | Sitemap | Contact