Java Singleton

What is Singleton??

Singleton is one of the "gangs of four" Design pattern, It comes under creation al Design pattern
it restrict of only single object of the class in the application
it does not restrict the creation of object on different JVM, Per JVM single instance

Basics to create the singleton object
1-Override the private constructor to prevent the creation of the object with new keyword
2-Declare one private static instance of the same class
        so that it can be available after the class load and you dont need to create the instance of the class to access it

3- public static method that will return the instance of the class

Example to create Singleton

Type-1
1- simple singleton

public class Singleton {
     private static Singleton instance = null;
     private Singleton() {
    }
     public static Singleton getInstance() {
        if (instance == null) {
            instance = new Singleton();
        }
        return instance;
    }
 }


Interview Ques -
Now if two or more thread access the singleton class can create as many as 
instance if at steps if(instance==null) they are at the same time


There are 3 ways in which we can achieve the thread safety

1- Creation of the instance at the time of the class loading
in it create a Static block and create your instance in it.


Type-2 public class Person { static { instance = new Person(); } private static Person instance = null; private Person() { } public static Person getInstance() { return instance; } }


You cannot do this in initialization block because it runs at the time of 
creation of object before constructor so you will end up in 
StackOverFlowexception

this is not a very user friendly wastage of resources if not used and also
always have generic type of instance

Type-3
2- Synchronized getinstance() method

Type-4
3-Synchronized block inside if, this is double checking i.e. we are only taking the lock to create the instance not to check whether the instance exists
 
public static Person getInstance(){ if(instance==null){ synchronized(timePassObject) { if(instance==null) instance= new Person(); } } return instance; }
we cannot use synchronized(this) because this can never be referenced by static 
context

you can synchronized on class level, lock by synchronized(Person.class)


Type-5

All the previous type refers to lazy initialization of object
Eager initialization
public class Singleton {
private static Singleton singleInstance = new Singleton();
private Singleton() {}
public static Singleton getSingleInstance() {
return singleInstance;
}
}



Type-6

Using serialization the singleton concept can be broken
you can serialize and de-serialize and get the new instance of the singleton class
to prevent this override the readResolve() method
This method will be invoked when you will de-serialize the object

ANY-ACCESS-MODIFIER Object readResolve() throws ObjectStreamException


or


you may return the same instance from the readResolve()
protected Object readResolve() {
        return instance;
    }


Type-7
Bill Pugh solution
Bill pugh was main force behind java memory model changes. His principle “Initialization-on-demand holder idiom
it suggest the static inner Class

public class BillPughSingleton {
    private BillPughSingleton() {
    }
   private static class LazyHolder {
        private static final BillPughSingleton INSTANCE = new BillPughSingleton();
    }
   public static BillPughSingleton getInstance() {
        return LazyHolder.INSTANCE;
    }
}

Type-8
The Best Using ENUM
Enum are compile time constants
public enum EnumSingleton {
     INSTANCE;
      public static void doSomething(){
        //do something
    }
}

Note - you can create the new object of your singleton class by Java Reflection API

Constructor[] constructors = Singleton.class.getDeclaredConstructors();
            for (Constructor constructor : constructors) {
                //Below code will destroy the singleton pattern
                constructor.setAccessible(true);
                instanceTwo = (Singleton) constructor.newInstance();
                break;

}



Comments