Brucalipto.org

Keep your door open!

Singleton Pattern: SingletonHolder

| Comments

Writing a singleton is not that hard but writing it the right way may not be all that trivial. I wrote hundreds singletons in my developer life and yesterday I found, thanks to a Wikipedia post, what I think is the perfect solution. The solution is not mine but I report it here for future reference:

Singleton.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
public class Singleton
{
  // Private constructor prevents instantiation from other classes
  private Singleton(){}

  /**
  * SingletonHolder is loaded on the first execution of Singleton.getInstance() 
  * or the first access to SingletonHolder.INSTANCE, not before.
  */
  private final static class SingletonHolder
  {
      private final static Singleton instance = new Singleton();
  }

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

In this implementation the singleton instance is thread safe and unique as this is warranted by using final and static keywords. Moreover the singleton instantiation is as lazy as possible: the singleton instance will be created if and only if you call the getInstance() method and not whenever you simply reference the Singleton class (like accessing a constant).

Comments