Is there a functional difference between initializing singleton in a getInstance() method, or in the instance variable definition

lbenedetto :

Is there any functional difference between these two ways of implementing a Singleton?

public class MySingleton {
    private static MySingleton instance;

    public static MySingleton getInstance() {
        if (instance == null) {
            instance = new MySingleton();
        }
        return instance;
    }
}


public class MySingleton {
    private static final MySingleton instance = new MySingleton();

    public static MySingleton getInstance() {
        return instance;
    }
}

Besides the fact that the first way would allow for some sort of clearInstance() method. Though you could just make instance not final in the second method.

Does the first method technically perform better because it is only initialized the first time it is needed instead of when the program starts?

Majid :

The first one is lazy loading and the second is eager loading. Maybe your application never call the singleton, so if creating new instance of your singleton be heavy resource consuming action, then the lazy loading is better since it create new instance once needed.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=84955&siteId=1