简体   繁体   中英

Singleton - Best way to instantiate class

I was looking at Telegrams's messenger source code and I noticed that their singleton classes all use local variables on their getInstance methods, just like below. For example, on their Android GitHub repo , on class NotificationsController.java they have the following:

private static volatile NotificationsController Instance = null;
public static NotificationsController getInstance() {
    NotificationsController localInstance = Instance;
    if (localInstance == null) {
        synchronized (MessagesController.class) {
            localInstance = Instance;
            if (localInstance == null) {
                Instance = localInstance = new NotificationsController();
            }
        }
    }
    return localInstance;
}

I'm not entirely sure what is the purpose of the local var "localInstance" there. Can anyone explain exactly what is the purpose of the "localInstance" var? Could not the same be achieved without it, just like in the code below?

private static volatile NotificationsController Instance = null;
public static NotificationsController getInstance() {
    if (Instance == null) {
        synchronized (MessagesController.class) {
            if (Instance == null) {
                Instance = new NotificationsController();
            }
        }
    }
    return Instance;
}

This is done for performance reasons.

Consider the most common scenario where the variable has been initialized. The code as written will read the volatile variable once and return the value. Your version would read it twice. Since volatile reads carry a slight performance cost, using the local variable can be faster.

Because in your case the lazily initialized variable is a static, it is preferable to use the holder class idiom. See this answer for an example.

确保这篇关于“Java 中的安全发布”的文章http://shipilev.net/blog/2014/safe-public-construction/将帮助您了解它是如何用于单音的

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM