Implementing Singleton in Java
Implementing the Singleton pattern in Java can be done in various ways, each with its own advantages and considerations. Two common methods are Lazy Initialization and Eager Initialization.
Lazy Initialization
Lazy Initialization is a technique where the instance of the class is created only when it is needed. This approach is memory efficient, as the instance is not created at class loading time. However, it is not thread-safe without additional synchronization.
1 2 3 4 5 6 7 8 9 10 |
public class Singleton { private static Singleton instance; private Singleton() {} public static Singleton getInstance() { if (instance == null) { instance = new Singleton(); } return instance; } } |
Eager Initialization
In Eager Initialization, the instance of the Singleton class is created at the time of class loading. This approach is simpler and thread-safe but may consume more memory as the instance is created irrespective of whether it’s needed or not.
1 2 3 4 5 6 7 |
public class Singleton { private static final Singleton instance = new Singleton(); private Singleton() {} public static Singleton getInstance() { return instance; } } |