Rod Waldhoff's Weblog  

Implementing the Singleton Pattern in Java

This is a copy of a 8 August 1998 article I had originally published on my Tripod site, which strangely seems to still get a number of hits. I've moved it here as a step toward shutting down that site.

Sometimes it is necessary, and it is often sufficient, to create a single instance of a given class. This has advantages in memory management, and for Java, in garbage collection. Moreover, restricting the number of instances may be necessary or desirable for technological or business reasons--for example, we may only want a single instance of a pool of database connections.

A simple approach to this situation is to use static members and methods for the "singleton" functionality. For these elements, no instance is required. The class can be made final with a private constructor in order to prevent any instance of the class from being created.

Unfortunately, this "static-singleton" approach falls short on several counts:

  1. We may require run-time information to prepare the static-singleton for use. It may be awkward to accomplish this--i.e., we must insure that the static-singleton is properly initialized before each use. This greatly increases the coupling between the static-singleton utility and its clients.
  2. Methods that are static cannot be used to implement an interface. Hence we lose a great deal of the power of Java's interface entity.
  3. All references to the singleton must be hard-coded with the name of the class. Hence there is no meaningful way to override the static methods. In other words, all static methods may as well be final.

The Singleton pattern, as described in the Gang-of-Four's Design Patterns, mitigates the first and second problem by creating a static wrapper around a reference to an instance of the Singleton class. Here's a Java implementation of their example, which uses static methods in the class itself as the "singleton-wrapper".

/**
 * A utility class of which at most one instance
 * can exist per VM.
 *
 * Use Singleton.instance() to access this
 * instance.
 */
public class Singleton {
   /**
    * The constructor could be made private
    * to prevent others from instantiating this class.
    * But this would also make it impossible to
    * create instances of Singleton subclasses.
    */
   protected Singleton() {
     // ...
   }
 

   /**
    * A handle to the unique Singleton instance.
    */
   static private Singleton _instance = null;
 
   /**
    * @return The unique instance of this class.
    */
   static public Singleton instance() {
      if(null == _instance) {
         _instance = new Singleton();
      }
      return _instance;
   }
 
 
   /. ...additional methods omitted...
}

If run-time information is required, it can be determined inside the private constructor. For the subclassing issue, the GOF describe a second approach that uses a registry, which is essentially a static hash-table for mapping keys to Singleton instances. This allows us to subclass the Singleton, as long as we know which specific subclass we want to use at a given point in the code. Here's a Java implementation:

import java.util.Hashtable;
 
/**
 * Use Singleton.instance(String) to access a given
 * instance by name.
 */
public class Singleton {
   static private Hashtable _registry = new Hashtable();
 
 
   // A static initializer that creates an instance of
   // this class and adds it to the registry when
   // the byte-code for this class is first loaded
   static {
      Singleton foo = new Singleton();
      _registry.put(foo.getClass().getName(),foo)
   }

   /**
    * The constructor could be made private
    * to prevent others from instatiating this class.
    * But this would also make it impossible to
    * create instances of Singleton subclasses.
    */
   protected Singleton() {
     // ...
   }
 
 
   /**
    * @return The unique instance of the specified class.
    */
   static public Singleton instance(String byname) {
      return (Singleton)(_registry.get(byname));
   }
 
   // ...additional methods omitted...
}

While this approach allows us to subclass the root Singleton class, clients still must know which subclass (by name) they want to access. (Note that we need not use the name of the class as the key to the hashtable, but clients must still choose which instance to request at run-time.) In other words, this addresses the first and second problems, but not the third, unless a parameter is used to hold the name of the class to reference. We would like to reduce this coupling.

In addition, the registry strategy suffers from a weaker form of the drawback noted by the GoF, namely that an instance of all Singleton classes above the chosen subclass is automatically created, whether or not it is actually used.

I prefer an alternate implementation, which frees clients from the responsibility of determining which subclass to reference, although this decision must be made at some prior point in the code. (A compile-time or run-time default can easily be provided, and the subclass to use can be dynamically altered at run-time.)

First, we create an interface for objects that create instances of the Singleton class. This is essentially a combination of the Abstract Factory, Factory Method and Functor patterns in the GoF book.

/**
 * An interface defining objects that can create Singleton
 * instances.
 */
public interface SingletonFactoryFunctor {
   /**
    * @return An instance of the Singleton.
    */
   public Singleton makeInstance();
}

Second, we create static wrapper for the Singleton class. Note that by separating the wrapper from the actual implementation, it is possible to both A) provide a well known access point for the Singleton instance and B) allow greater flexiblity as to which subclass to use to create the instance. Note that the wrapper could actually wrap a Singleton interface, rather than a concrete class.

/**
 * A static container for a single instance of the Singleton
 */
final public class SingletonWrapper {

   /**
    * A reference to a possibly alternate factory.
    */
 
   static private SingletonFactoryFunctor _factory = null;

   /**
    * A reference to the current instance.
    */
   static private Singleton _instance = null;
 

   /**
    * This is the default factory method.
    * It is called to create a new Singleton when
    * a new instance is needed and _factory is null.
    */
   static private Singleton makeInstance() {
      return new Singleton();
   }

   /**
    * This is the accessor for the Singleton.
    */
   static public synchronized Singleton instance() {
      if(null == _instance) {
         _instance = (null == _factory) ? makeInstance() : _factory.makeInstance();
      }
      return _instance;
   }
 
   /**
    * Sets the factory method used to create new instances.
    * You can set the factory method to null to use the default method.
    * @param factory The Singleton factory
    */
   static public synchronized void setFactory(SingletonFactoryFunctor factory) {
      _factory = factory;
   }
 
   /**
    * Sets the current Singleton instance.
    * You can set this to null to force a new instance to be created the
    * next time instance() is called.
    * @param instance The Singleton instance to use.
    */
   static public synchronized void setInstance(Singleton instance) {
      _instance = instance;
   }
 
}

Clients that use this SingletonWrapper need only use something like SingletonWrapper.instance().method().

Note that since SingletonWrapper is final, the instance method can essentially be inlined. Hence the only real over-head here is the check if _instance is null. (Even this could be removed, if we refactor the class to ensure that _instance is never null. For example:

  • create a new instance when the class is loaded via a static initializer
  • create a new instance when a new factory is assigned via setFactory
  • make sure setInstance is never used to change _instance to null, or create a new instance if it is)

This approach allows us to easily alter the specific Singleton instance published--either dynamically or at compile-time--without altering the code that uses the Singleton. Moreover, the Singleton itself need not be aware of the Singleton functionality. Hence this SingletonWrapper can be created for pre-existing classes such as those provided with an API or framework.