Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 379
lbenedetto Avatar asked Apr 30 '26 16:04

lbenedetto


1 Answers

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.

like image 188
Majid Avatar answered May 03 '26 05:05

Majid