Monday, January 25, 2010

Singleton Pattern in Java

The singleton pattern ensures that there is exactly one instance of a class.

There are multiple ways to implement the Singleton Pattern in Java, here is my personal favorite:


 
public final class SomeClass {
 
  private static final class SingletonHolder {
    private static final SomeClass INSTANCE = new SomeClass();
    private SingletonHolder() {}
  }
 
  private SomeClass() {
    // Add code if needed
  }
 
  /**
    * @return the Singleton Instance.
    */
  public static SomeClass getInstance() {
    return SomeClass.SingletonHolder.INSTANCE;
  }
 
  // add other methods
 
}

Notes:

  • Replace SomeClass with the class name, keep all other names exactly as given.
  • Class is final to ensure its constructor cannot be made public by subclassing.
  • The SingletonHolder nested class enables lazy loading and ensures synchronization without performance loss.
  • Constructor must be made private.
  • getInstance returns the singleton instance of this class.

4 comments:

  1. is this thread safe? i've always put the assignment of the static variable in the constructor, guarded by a lock clause...

    ReplyDelete
  2. Yes, this is Thread safe. The trick is that the static assignment is handled by the classloader, which is thread safe by definition (and 'faster' in locking than using synchronized{} )

    ReplyDelete
  3. Nice article. just to add
    While writing Singleton class you also need to consider following points :
    1) Lazy initialization
    2) Early initialization
    3) Serialization
    4) Many ClassLoaders
    5) Cloning

    Thanks
    Javin
    Singleton Pattern in Java

    ReplyDelete