我正在学习Android,并且一直在浏览Android Studio 3.4.1提供的基本项目模板。名为“Login Activity”(可通过新项目访问…)的程序在Login Repository.java中使用存储库类设置一个实现

public class LoginRepository {

private static volatile LoginRepository instance;

private LoginDataSource dataSource;

private LoggedInUser user = null;

// private constructor : singleton access

private LoginRepository(LoginDataSource dataSource) {

this.dataSource = dataSource;

}

public static LoginRepository getInstance(LoginDataSource dataSource) {

if (instance == null) {

instance = new LoginRepository(dataSource);

}

return instance;

}

// other methods excluded for simplicity

}

}

使用

volatile

暗示他们想要线程安全(尽管我不知道为什么,因为它看起来是一个单线程应用)。

如果需要线程安全,为什么没有

synchronized

在getInstance方法中?

如果不需要线程安全,为什么

不稳定的

使用过?

我知道有可能

不稳定的

没有

同步的

在多线程情况下

this other question

但在我们的情况下,我们只做了一个单子。

谢谢

Logo

华为开发者空间,是为全球开发者打造的专属开发空间,汇聚了华为优质开发资源及工具,致力于让每一位开发者拥有一台云主机,基于华为根生态开发、创新。

更多推荐