I've found the following code in a Google sample project, a simple getInstance()
method implementation for a singleton:
public static AppDatabase getInstance(final Context context, final AppExecutors executors) {
if (sInstance == null) {
synchronized (AppDatabase.class) {
if (sInstance == null) { // why do we check this?
sInstance = buildDatabase(context.getApplicationContext(), executors);
sInstance.updateDatabaseCreated(context.getApplicationContext());
}
}
}
return sInstance;
}
It's perfectly clear why we're checking sInstance
for null
the first time, but why do we check it inside the synchronized
block as well?
I'd really appreciate if someone could explain this.