Dr Jorge
Dr Jorge

Reputation: 363

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;
}

Upvotes: 2

Views: 379

Answers (2)

ivanenok
ivanenok

Reputation: 614

Sure this article about "Safe publication in Java" http://shipilev.net/blog/2014/safe-public-construction/ will help you to understand how it works for singletones

Upvotes: 0

Misha
Misha

Reputation: 28133

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.

Upvotes: 1

Related Questions