2

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.

justanoob
  • 1,797
  • 11
  • 27
  • https://en.wikipedia.org/wiki/Double-checked_locking – luk2302 Mar 28 '18 at 08:27
  • Note that singletons constructed using user-supplied parameters are fishy. What happens when you call the method a second time with different parameters? You *think* you got an instance using `context2`, but actually you have an instance using `context1`. – Andy Turner Mar 28 '18 at 08:32
  • @AndyTurner isn't that the reason why `context.getApplicationContext()` is called? – justanoob Mar 28 '18 at 08:34
  • 1
    OK, same point, with `executors1` vs `executors2`. – Andy Turner Mar 28 '18 at 08:35

0 Answers0