Skip to content

Instantly share code, notes, and snippets.

@rajeakshay
Created August 8, 2016 23:06
Show Gist options
  • Save rajeakshay/740396741a720652506a2c7f0963771b to your computer and use it in GitHub Desktop.
Save rajeakshay/740396741a720652506a2c7f0963771b to your computer and use it in GitHub Desktop.
Two primary approaches of implementing a Singleton class in Java.
/**
*
* Thread-safe singleton with lazy initialization. (Bill Pugh's approach)
*
* NOTES -
* When BillPughSingleton class is loaded, SingletonHelper class is not loaded into memory. Only when someone calls
* getInstance() method, does the SingletonHelper class gets loaded and creates a BillPughSingleton instance.
*
* The advantage comes from the lazy initialization. BillPughSingleton instance, which might be potentially consuming
* very high memory, will only be created when getInstance is called the first time.
*
* Bill Pugh's approach is thread-safe because JLS specifies that class loading is thread-safe. Hence, only one thread
* can kick-off the loading of SingletonHelper class and until that operation has not finished, another thread cannot
* interact with SingletonHelper class. As a result, there will only be one instance of BillPughSingleton even in
* multi-threaded programs.
*
*/
public class BillPughSingleton {
private BillPughSingleton(){}
private static class SingletonHelper{
private static final BillPughSingleton INSTANCE = new BillPughSingleton();
}
public static BillPughSingleton getInstance(){
return SingletonHelper.INSTANCE;
}
}
/**
*
* Thread-safe singleton class with double-checked locking principle.
*
*/
public class DoubleCheckedLocking {
/**
* Without the volatile modifier it is possible for another thread in Java
* to see half-initialized state of _instance variable. With volatile modifier
* there is a happens-before guarantee -> all write will happen on volatile
* _instance before any read of _instance variable.
*/
private volatile static DoubleCheckedLocking _instance;
private DoubleCheckedLocking(){}
public static DoubleCheckedLocking getInstance(){
if(_instance == null){ // First check
/**
* synchronized block ensures that only one instance of DoubleCheckedLocking is created.
*/
synchronized(DoubleCheckedLocking.class){
if(_instance == null){ // Second check
_instance = new DoubleCheckedLocking();
}
}
}
return _instance;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment