Does this code solve the double checked locking issue in Java?
public class DBAccessService() {
private static DBAccessService INSTANCE;
private DBAccessService() {}
public static DBAccessService getInstance() {
if (INSTANCE != null) {
return INSTANCE;
}
return createInstance();
}
private static synchronized DBAccessService createInstance() {
if (INSTANCE != null) {
return INSTANCE;
}
DBAccessService instance = new DBAccessService();
INSTANCE = instance;
return INSTANCE;
}
}
There are 2 aspects to pay attention:
getInstance()
is not synchronized, so after INSTANCE is initialized there is no cost for synchronizationcreateInstance()
is synchronized
So, the question is: does this code have any issues? Is it legal and always thread-safe?