dimanche 29 mars 2015

Avoid lazy loading by ensuring that there is only one static method in a Singleton class

Disclaimer : I am aware that using an enum is one of the most effective ways of creating a Singleton so let's keep this argument aside for now. I am also aware that Singleton is considered an anti-pattern for some use cases so let's leave this aside as well.


The two basic use cases for a class to be loaded in the JVM are:



  1. An instance of the class is created using the new operator (e.g. new MyClass())

  2. The class is referenced in a static context (e.g. System.out.println())


Let's consider an example of Singleton that does not use lazy loading.



public class Singleton {
private static final Singleton INSTANCE = new Singleton();

private Singleton() { }

public static Singleton getInstance() {
return INSTANCE;
}

public static void someStaticMethod() {

}
}


Sine this class has a private constructor, it's not possible to instantiate it using the new keyword. While it is possible to use reflection to create an instance of the class, let's leave that argument aside for now. So the only other way that this class will get loaded is that you refer to it in a static context.


There are two mutually exclusive use-cases for using the class in a static context :



  1. We call someStaticMethod without calling getInstance first.

  2. We call getInstance to get a reference to the only instance of the class.


We only need lazy loading if we ever have to exercise use case 1 in our application. If we don't exercise use case one in our application, we never need lazy loading because when we call getInstance, we intend to load the instance of the class.


This brings me to the question. Instead of worrying about lazy loading, wouldn't it be better that the standard way to implement a Singleton using a class is to ensure that the only static method in the Singleton class is the getInstance method? Besides, having a static method other than the getInstance method in a Singleton class would mean that we are mixing the use case of a static class and a singleton class in one class which IMO should not be done in the first place. What's the fuss about lazy-loading a Singleton anyway?


Aucun commentaire:

Enregistrer un commentaire