Thursday, May 10, 2012

Initialization-on-demand holder idiom


Almost everyone knows how the singleton pattern works. It looks something as follows:

class Singleton
{
private static Singleton _instance;

private Singleton(){ }

public Singleton getInstance()
{
   if(_instance == null)
  {
     _instance = new Singleton();
  } 

  return _instance;
} 

} 

This code would won't correctly in case of an multi-threaded environment. For it to work in a multi-threaded environment you will add some synchronization code.

However I came across this new way to assure singleton instance in Java. It is called Initialization-on-demand holder idiom. You can read about it here: http://en.wikipedia.org/wiki/Initialization_on_demand_holder_idiom

It relies on the defined initialization phase of execution within the JVM.

No comments:

Post a Comment