outer if (instance == null) is for performance and inner if (instance == null) is ensuring the singleton creation.
Suppose we dont have any if (instance == null) the our code become as below,
// double locking is used to reduce the overhead of the synchronized method
public static ThreadSafeSingleton getInstanceDoubleLocking() {
synchronized (ThreadSafeSingleton.class) {
// any number of thread can enter this block one by one and can create new instance
instance = new ThreadSafeSingleton();
}
return instance;
}
threads can enter one by one but only one thread can create object after that other threads can enter the block but can not create instance but unnecessary they are entering into syncronization block. So putting outer if condition prevent later threads to enter synchronization block.
public static ThreadSafeSingleton getInstanceDoubleLocking() {
synchronized (ThreadSafeSingleton.class) {
// threads can enter one by one but only one thread can create object after that other threads can enter the block but can not create instance but unnecessary they are entering into syncronization block. So putting outer if condition prevent later threads to enter synchronization block.
if (instance == null) {
instance = new ThreadSafeSingleton();
}
}
return instance;
}