Singleton Pattern
 

- JavaTouch

- Design Patterns Home

- Factory Pattern

- Inversion of Control (IoC)Pattern

 

Singleton Pattern:

Ensures a class has only one instance, and provide global point of access to it.

 

Limitations in use of Singleton

When designing systems targeted for a distributed environment with multiple JVM, the Singleton should not be used and is bad programming. The benefits of its use are extremely outweighed by the problems and issues it carries when applied to larger systems, especially enterprise-level J2EE-based systems. Singletons hamper scaling and extensibility efforts in the context of distributed applications.
(Ref: Wegainfinance blogger )



More Links in Singleton Pattern

- Singleton Pattern Home at Wiki
- Simply Singleton (from JavaWorld)
- Description of Singleton (from dofactory)
- Double-checked locking and the Singleton pattern (from IBM)


 Recommended Book


Shoes . . .

As Mahatma Gandhi stepped aboard a train one day, one of his shoes slipped  off and landed on the track. He was unable to retrieve it as the train was moving.
 
To the amazement of his companions, Gandhi calmly took off his other shoe and threw it back along the track to land close to the first.
 
Asked by a fellow passenger why he did so, Gandhi smiled. "The poor man who finds the shoes lying on the track," he replied, "will now have a pair he can use."

In object-oriented design, the Singleton design pattern is used to restrict instantiation of a class to one object. This is useful when exactly one object is needed to coordinate actions across the system. Sometimes it is generalized to systems that operate more efficiently when only one or a few objects exist.


Implementation Insight

The Singleton pattern is implemented by creating a class with a method that creates a new instance of the object if one does not exist. If an instance already exists, it simply returns a reference to that object. To make sure that the object cannot be instantiated any other way, the constructor is made either private or protected. Note the distinction between a simple static instance of a class and a singleton. Although a Singleton can be implemented as a static instance, it can also be lazily constructed, requiring no memory or resources until needed.

 


  

Java example implementation (simple non threadsafe)

public class Singleton {

  private static Singleton uniqueInstance;

  // constructor is declared private, so only singalton can instantiate 
  private
Singleton() {}

   public static final Singleton getInstance() {
     if  (uniqueInstance == null )
          uniqueInstance = new  Singleton();
     }
     return uniqueInstance;

Notes:

1. Our constructor is declared private; only Singleton can instantiate this class.

 

The Multithread Issue

The Singleton pattern must be carefully constructed in multi-threaded applications. If two threads are to execute the creation method at the same time when a Singleton does not yet exist, they both must check for an instance of the Singleton and then only one should create the new one. If the programming language has concurrent processing capabilities the method should be constructed to execute as a mutually exclusive operation.

 

The ThreadSafe Singleton Implementations

Java threadsafe implementation 1

A correct threadsafe Java programming language lazy-loaded solution known as the "Initialization On Demand Holder (IODH)" idiom.

public final class Singleton {
/* Private constructor suppresses generation of a (public) default constructor */
   private Singleton() {}

   private static class SingletonHolder {
     private static Singleton uniqueInstance= new Singleton();
   }

   public static final Singleton getInstance() {
     return SingletonHolder.uniqueInstance;
   }
}

Notes:
Basicaly, Java Language Specification (JLS) guarantees that instance would not be initialized until someone calls getInstance() method
- Lazy instantiation
- No synchrronized (performance intensive)  method used
- Lack of any public actors (only the getInstance method is made public)  makes it impossible to subclass this class in non thread safe manner.
- Making it final speak it better.

 

Java threadsafe implementation 2

public final class Singleton{
    private static final Singleton uniqueInstance= new Singleton();
 
    private Singleton() {}
 
    public static finalSingleton getInstance() {
        returnuniqueInstance;
    }
}

Notes:
- No lazy instantiation
- Sufficient for allmost all the cases

 

Java threadsafe implementation 3

public final class Singleton {
   private static final Singleton uniqueInstance;
   
    private Singleton() {
   }
  
   public static final synchronizedSingleton getInstance() {
     if(uniqueInstance== null) {
              uniqueInstance= new Singleton();
      }
     returnuniqueInstance;
   }
}

Notes:
- The problem with this solution is that synchronized method getInstance() is called every time, while synchronization is actually needed only for the first call of the method (which introduces performance overhead in your application).
- Therefore this implementation is not prefered in most cases due to performance concern

 
An Incorrect ThreadSafe Singleton Implementation !

An incorrect Java programming language lazy-loaded solution known as the "Initialization On Demand Holder" idiom suggested by Pankaj Jaiswal. Double-checked locking is not guaranteed to work. ( Ref: Wiki )

public class Singleton {
   private static Singleton uniqueInstance;
  
   /* Private constructor suppresses generation of a (public) default      
   constructor */

   private Singleton() {
   }
  
   public static Singleton getInstance() {
     if(uniqueInstance== null) {
        // Not guaranteed to work
        synchronized (Singleton.class) {
           if(uniqueInstance== null) {
              uniqueInstance= new Singleton();
           }
        }
     }
     returnuniqueInstance;
   }
}

Notes:

 - This is another proposed lazy-loaded solution to improve performance concern in solution 3
- Here the performance intensive synchronisation block is called only in the fist time
- This uses double-checked locking. However, DCL presented there does not work. Since DCL's job is to guarantee that only one instance is created and that it's not used before construction is complete, and since it can't make that guarantee, it does not work!!.
- So do not use this implementation though found in some resources.

 References:
- Head First Design Patterns (Head First)
- Lazy Loading Singletons (Jan 2007, Bob Lee's Blog)
- Singletons and lazy loading (Jan 2007, OnJava)

Current Rating: Rate This Artical:

Your Feedback: