Sunday, 8 July 2012

Singleton Pattern

The Singleton pattern allows you to take control of object creation by ensuring that only one instance of a class is instantiated. This can be useful when you want to restrict resource use, or you have a sensitive object whose data shouldn’t be accessed by multiple instances (a registery object for example).
Imagine you have an object containing a large amount of reference data that you want to share across your application - you may want to ensure that you have only one instance of that object. Multiple instances of such a large object would unnecessarily increase the memory footprint of your application.

Typically objects are instantiated using the new operator - the following 3 lines of code will create 3 new ReferenceData objects.
    
    ReferenceData refData1 = new ReferenceData();
    ReferenceData refData2 = new ReferenceData();
    ReferenceData refData3 = new ReferenceData();
The Singleton pattern restricts the use of the new operator and ensures that only one instance of a class is created and shared across the application. But how do we actually stop our application creating more than once instance of a class? We simply make the constructor private so that it cannot be called form outside its own class as shown below.
    
public class ReferenceData
{
     private ReferenceData()
     {

     }
}    
Implementing the Singleton Pattern
At this point you’re probably thinking, if we can’t use the ReferenceDataSingleton constructor then how do we actually create an instance of the object?
We take care of this by using a static utility method to create and return an instance of the class as shown below. The standard naming convention for such a utility method is getInstance.
The code above is pretty simple but I’ll explain it below anyway.
public class ReferenceDataSingleton
{
     // because referenceDataSingleton is private it cannot be 
      // accessed from outside this class - the only way it can be 
      // accessed is via the static getInstance utility method below
      private static ReferenceDataSingleton referenceDataSingleton;

      private ReferenceDataSingleton()
      {

      }

      public static ReferenceDataSingleton getInstance()
      {
           // if referenceDataSingleton is null then we'll create a 
           // new instance of this object. We use the constructor
           // (even though its private) because we're creating the object 
           // inside the class itself */
           if(null==referenceDataSingleton)
           {
                referenceDataSingleton = new ReferenceDataSingleton();
           }

           // return the single instance of referenceDataSingleton 
           // each time this method is called
           return referenceDataSingleton;
      }
}
Line 6 - a reference to ReferenceDataSingleton is marked as private so that it cannot be accessed from outside the class. It’s also marked as static so that the reference is tied to the class and not an instance of the class - this means it can be referenced from the getInstance static utility method.

Line 8 - a private constructor ensures that instances of this class cannot be created from outside the class and forces external code to access this object via its static utility method as opposed to creating a new instance using the new operator.

Line 13 - Static utility method returns an instance of this class to the calling code. A new instance is only created and assigned to the static class variable if it does not already exist. Subsequent calls to this utility method will return the existing ReferenceDataSingleton reference. This ensures that no matter how many times this function is called it will always return a reference to the same instance of this class.
Calling the getInstance method returns a ReferenceDataSingleton object
Calling getInstance for a second time will return the same object as before. No matter how many times getInstance is called the same object is always returned.
Ensuring Thread Safety
While the code above will work fine in most instances there is still a potential flaw.
Can you spot the issue? Take a look at line 19 - here we check whether or not the class variable referenceDataSingleton has already been set and we only create a new instance if it is null. Imagine we have 2 threads that both check this condition at the same time - both threads could check this condition at the same time and find referenceDataSingleton is null, then both threads would create new instances of ReferenceDataSingleton on line 21. This would result in 2 separate instances of ReferenceDataSingleton being created, which could lead to havoc if our application thinks its dealing with a singleton.
At this point you're probably wondering how we get around this issue  - don't worry because I've described 2 possible solutions to this problem below.

Solution 1 - Mark method as synchronised
    
public static synchronized ReferenceDataSingleton getInstance()
{
      // if referenceDataSingleton is null then we'll create a
      // new instance of this object. We use the constructor
      // (even though its private) because we're creating the object
      // inside the class itself 
      if(null==referenceDataSingleton)
      {
           referenceDataSingleton = new ReferenceDataSingleton();
      }

      // return the single instance of referenceDataSingleton
      // each time this method is called 
      return referenceDataSingleton;
}    
By marking our getInstance method as synchronised we ensure that only one thread can execute the method at any time. While this is effective it can introduce a significant performance overhead by blocking new threads entering the method until the currently executing thread is finished.

Solution 2 – Create new instance outside of getInstance method
This approach removes the object creation code form the getInstance method and makes sure that the object is already created before the method is even called. We do this by instantiating ReferenceDataSingleton when the class is created and simply returns the reference to this object from getInstance.
    
public class ReferenceDataSingleton
{
      // because referenceDataSingleton is private it cannot be
      // accessed from outside this class - create a new instance of
      // this class which will be returned by the getIndssdtance utility
      // method below 
      //
      private static ReferenceDataSingleton referenceDataSingleton = new ReferenceDataSingleton();

      private ReferenceDataSingleton()
      {

      }

      public static synchronized ReferenceDataSingleton getInstance()
      {
            // return the single instance of referenceDataSingleton
     // each time this method is called             
     return referenceDataSingleton;
      }
}
This approach means we no longer have the performance overhead of a synchronised utility method yet we are still guaranteed that only one instance of the object will ever be created. Given there are no performance implications I’d recommend this approach over the synchronised method solution mentioned above.

Side Note
If you are using multiple class loaders with Singletons you may run into issues. Each class loader uses its own namespace so you may in fact end up with multiple Singleton objects (one per class loader). You’ll need to take the necessary steps to ensure that this doesn’t happen - I’ll not get into this now as it’s beyond the scope of this post but it’s definitely something you should be aware of.

Summary
The Singleton pattern allows you to ensure that only one instance of an object is created and shared across your application. This can be useful when you want to restrict resource use or have a sensitive object whose data shouldn’t be accessed by multiple instances.

3 comments:

  1. This comment has been removed by the author.

    ReplyDelete
  2. Nice Post and more informative.

    For more on Spring and webservices fallow us on http://javasourceworld.blogspot.in/

    ReplyDelete
  3. http://javasourceworld.blogspot.in/

    ReplyDelete