Singleton for multithreading in Java
Everyone knows what is singleton pattern, but how to implement a singleton class in multithreaded environment? Next, I’m going to present best approaches for this use case.
Bill Pugh Singleton Implementation
public class Singleton { private Singleton() { } private static class SingletonHolder { private static final Singleton INSTANCE = new Singleton(); } public static Singleton getInstance() { return SingletonHolder.INSTANCE; } }
Thread Safe Double Checked Singleton Implementation
public class Singleton { private static Singleton instance; private Singleton() { } public static Singleton getInstance() { if(instance == null) { synchronize (Singleton.class) { if(instance == null) { instance = new Singleton(); } } } return instance; } }