• Home
  • Singleton instance

Singleton instance

29 September 2009 Bajrang Gupta Comments Off

I came across a different way of creating Singleton instances, and now I think that should be the way.
Normally, I used to create singletons using a private constructor, and a getInstance method that would perform a null check, on whether the instance is already created. Now, if the instance is not created, we continue by creating an instance using the private constructor. However, this method is prone to concurrency, and we have to manually implement synchronization logic.

A more elegant way to do this could be as follows:
public class Singleton {
private Singleton() { }

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

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

The above method employs “initialization on demand holder” to create the singleton instance.