android studio登录活动,在Android Studio项目模板“登录活动”中使用volatile而不是synchronized for lazy singleton...
我正在学习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
但在我们的情况下,我们只做了一个单子。
谢谢
更多推荐



所有评论(0)