I am learning Android and have been looking through the base project templates provided by Android Studio 3.4.1. The one called "Login Activity" (accessible via New Project...) sets up an implementation with a Repository class in LoginRepository.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
}
}
link to android.com description
link to another question with more of the app code
The use of volatile suggests they want thread-safety (although I'm not sure why since it appears to be a single-threaded app).
If thread-safety is needed then why isn't there a
synchronizedin the getInstance method?If thread-safety is not needed, why is
volatileused?
I understand there could be a use of volatile without synchronized in such multi-threaded cases as this other question but in our case we are making a singleton.
Thanks