I have developed singleton in many ways depending upon the condition like volatile/lazy singleton, eager singleton, normal singleton and through Enum also, but specifically I want to know about static holder pattern singleton shown below.
public static class Singleton {
private static class InstanceHolder {
public static Singleton instance = new Singleton();
}
private Singleton(){}
public static Singleton getInstance() {
return InstanceHolder.instance;
}
}
Please advise under which conditions it is beneficial and what are its benefits.
Singletons have a static property that you must access to get the object reference. So you are not instantiating an object such as in the manner we do for a normal class.
Singleton implementation can either have static members or instance members. Static classes can contain static members only. It can implement any other interface or base class is required. It cannot implement the interface or any other base class.
A singleton doesn't use static methods, so you won't have trouble using it in a non-static context. Singletons can be extended/subclassed. Since they're objects, they can be injected into other objects, which allow for the creation of some great design patterns utilizing the concepts of dependency injection.
In Java, Singleton is a design pattern that ensures that a class can only have one object. To create a singleton class, a class must implement the following properties: Create a private constructor of the class to restrict object creation outside of the class.
This pattern is beneficial for at least 3 reasons:
The JVM defers initializing the InstanceHolder class until it is actually used, and because the Singleton is initialized with a static initializer, no additional synchronization is needed. The first call to getInstance by any thread causes InstanceHolder to be loaded and initialized, at which time the initialization of the Singleton happens through the static initializer.
Static holder pattern is also considered as the smartest replace for Double-check-locking antipattern.
This is a way to make a thread-safe lazy singleton by exploiting the way how JVM loads classes. You can read more about why and how to correctly implement it in Bloch's Effective Java book.
Remember, that from the testable code
point of view singletons (and global state in general) are not beneficial and should be avoided.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With