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