Singleton Design Pattern in Java with example
Singleton Design Pattern is a software design pattern that makes sure you have only one instance of a class in the application or JVM. It is a type of creational design pattern. This is required when creating single instance of thread pool, cache manager, logging objects, printer objects, etc.
1) Implement Singleton Design Pattern with eagerly creating the instance
If your application always creates and uses an instance of the Singleton
or there is no overhead in creating the instance, you can create your Singleton
eagerly, like below. However with this approach, singleton instance creation is dependent on JVM classloader.
public class Singleton { private static Singleton singleton = new Singleton(); private Singleton() {} public static Singleton getInstance() { return singleton; } }
2) Implement Singleton Design Pattern with lazy loading approach
Sometimes the instance creation of a class may be expensive so you can create Singleton
instance lazily, like below.
However if multiple threads call getInstance()
they may end up with different instances of Singleton
class
which we want to avoid.
public class Singleton { private static Singleton singleton; private Singleton() {} public static Singleton getInstance() { if (singleton == null) { singleton = new Singleton(); } return singleton; } public static void main(String[] args) { System.out.println(Singleton.getInstance()); System.out.println(Singleton.getInstance()); } }
Output :
Singleton@7852e922 Singleton@7852e922
3) Implement Singleton Design Pattern with lazy loading approach and double-checked locking
To solve concurreny issue, we will mark the block that creates instance as synchronized
. Note that we could have marked
getInstance() method as synchronized
but it will have performance penalty.
public class Singleton { private volatile static Singleton singleton; private Singleton() {} public static Singleton getInstance() { if (singleton == null) { synchronized (Singleton.class) { if (singleton == null) { singleton = new Singleton(); } } } return singleton; } }
4) Implement Singleton Design Pattern using enum.
An enum
is instantiated only once, hence you can also create an enum
to create a Singleton class.
public enum SingletonEnum { INSTANCE; public static void main(String[] args) { System.out.println(SingletonEnum.INSTANCE); System.out.println(SingletonEnum.INSTANCE); } }
Output :
Singleton@7852e922 Singleton@7852e922