Thursday, May 2, 2013

What is Singleton class in java with example? How to create Singleton class?



Singleton class is a class which has only one instance in whole JVM.
Example of singleton class in jdk is java.lang.Runtime,  getRuntime() method is used to create instance.

There are following ways to create Singleton class

What is Early and Lazy loading of Singleton and how will you implement it?
Early Loading: Singleton instance is created when class is loaded into memory.
Lazy Loading: Singleton instance is not created when class is loaded into memory.  When we call its getInstance() method only then its instance is created.  Such kind of phenomena is called lazy loading.
e.g Early Loading
public class Singleton {
                public static final Singleton INSTANCE = new Singleton ();
                private Singleton (){
                }
}

Lazy Loading
public class Singleton {
                private static final Singleton INSTANCE = new Singleton ();
                private Singleton (){        }
                public Singleton getInstance(){
                                return INSTANCE;
                }
}

Double checked locking in Singleton
public static Singleton getInstance(){
     if(null == INSTANCE){
         synchronized(Singleton.class){
         //double checked locking - because second check of Singleton instance with lock
                if(null == INSTANCE){
                    INSTANCE = new Singleton();
                }
            }
         }
     return INSTANCE;
}
Double checked locking should only be used when you have requirement for lazy initialization otherwise use Enum to implement singleton or simple static final variable.

In Java 1.5, there is an approach to implementing singletons. Simply make an enum type with one element:
Singleton using Enum in Java
// Enum singleton - This is the preferred approach
public enum Elvis {
                INSTANCE;
}
This approach is functionally equivalent to the public field approach, except that it is more concise, provides the serialization machinery for free, and provides an ironclad guarantee against multiple instantiation, even in the face of sophisticated serialization or reflection attacks. While this approach has yet to be widely adopted, a single-element enum type is the best way to implement a singleton.