Java – is there a functional difference between initializing singletons in the getInstance () method or instance variable definition

Are there any functional differences between the two methods of implementing 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;
    }
}

In addition to the fact that the first method allows some clearinstance () method Although you can make the instance not final in the second method

Does the first method perform better technically because it initializes only the first time it is needed, not when the program starts?

Solution

The first is delayed loading, and the second is eager loading Perhaps your application never calls a singleton, so if creating a new instance of a singleton is a resource consuming operation, it is better to delay loading because it creates a new instance when needed

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>