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


  • 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.


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

  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{} )

  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

    Singleton Pattern in Java

  4. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Java developer learn from Java Training in Chennai. or learn thru Java Online Training India . Nowadays Java has tons of job opportunities on various vertical industry.

  5. Executive deferred payment, defined contribution etc. adp ipay login For big business it provides hire-to-retire remedy which takes care.