I came across a different way of creating Singleton instances, and now I think that should be the way. Normally, I used to create singletons using a private constructor, and a getInstance method that would perform a null check, on whether the instance is already created. Now, if the instance is not created, we continue by creating an instance using the private constructor. However, this method is prone to concurrency, and we have to manually implement synchronization logic.
A more elegant way to do this could be as follows: public class Singleton { private Singleton() { }
private static class SingletonHolder { static Singleton instance = new Singleton(); }
public static Singleton getInstance() { return SingletonHolder.instance; } }
Singleton instance
I came across a different way of creating Singleton instances, and now I think that should be the way.
Normally, I used to create singletons using a private constructor, and a getInstance method that would perform a null check, on whether the instance is already created. Now, if the instance is not created, we continue by creating an instance using the private constructor. However, this method is prone to concurrency, and we have to manually implement synchronization logic.
A more elegant way to do this could be as follows:
public class Singleton {
private Singleton() { }
private static class SingletonHolder {
static Singleton instance = new Singleton();
}
public static Singleton getInstance() {
return SingletonHolder.instance;
}
}
The above method employs “initialization on demand holder” to create the singleton instance.
Archives
Categories
Recent Posts
Stopping and Removing Containers
29 May 2019Installing Amazon CLI and Terraform on Windows desktop
27 May 2019Convert DOS to UNIX and vice versa
25 May 2019Calendar