Posts

Showing posts from January, 2017

Better ways to implement Singleton in Java

Singleton Design pattern restrict creation of only once instance of a Class. That means inside a single JVM only one instance of the Singleton Class will be created.  In java we have broadly two options to implement Singleton. 1) Early Creation of the Object Instance. 2) Lazy Creation of the Object Instance: Here the instance is created on first invocation. Following example demonstrate how to implement Singleton in Java. Method 1: Early Creation of Object Instance public class SingletonClass { private static final SingletonClass INSTANCE = new SingletonClass(); //Private Constructor private SingletonClass () { //Do nothing } public static SingletonClass getInstance () { return INSTANCE ; } } Here the instance is created ahead even before calling the Class. We need to provide a private constructor otherwise Java Compiler will add a default Constructor. Method 2: Lazy Creation of Object Inst...