[英]Singleton - Best way to instantiate class
我正在查看 Telegrams 的 messenger 源代碼,我注意到它們的單例類都在它們的 getInstance 方法上使用了局部變量,如下所示。 例如,在他們的Android GitHub repo 上,在類NotificationsController.java 上,他們有以下內容:
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;
}
我不完全確定那里的本地變量“localInstance”的目的是什么。 誰能解釋一下“localInstance”變量的目的是什么? 沒有它就不能實現,就像下面的代碼一樣?
private static volatile NotificationsController Instance = null;
public static NotificationsController getInstance() {
if (Instance == null) {
synchronized (MessagesController.class) {
if (Instance == null) {
Instance = new NotificationsController();
}
}
}
return Instance;
}
這樣做是出於性能原因。
考慮變量已初始化的最常見場景。 編寫的代碼將讀取 volatile 變量一次並返回值。 你的版本會讀兩遍。 由於 volatile 讀取會帶來輕微的性能成本,因此使用局部變量會更快。
因為在您的情況下,延遲初始化的變量是靜態的,所以最好使用 holder 類習語。 有關示例,請參閱此答案。
確保這篇關於“Java 中的安全發布”的文章http://shipilev.net/blog/2014/safe-public-construction/將幫助您了解它是如何用於單音的
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.