0

In a Sonar report at work we have a few warnings for an Android project:

Multithreaded correctness - Incorrect lazy initialization of static field findbugs : LI_LAZY_INIT_STATIC

In order to correct these issues I was directed to the wikipedia entry on double checked locking

http://en.wikipedia.org/wiki/Double_checked_locking_pattern#Usage_in_Java

When I look through the android framework code, I do not see double checked locking employed for example, the WebViewDatabase class just makes its getInstance(Context) method synchronized:

public static synchronized WebViewDatabase getInstance(Context context) {
    if (mInstance == null) {
        mInstance = new WebViewDatabase(context);
    }
    return mInstance;
}

What is the right way in Android?

Thanks in advance

Ian Warwick
  • 4,774
  • 3
  • 27
  • 27

1 Answers1

5

public static synchronized WebViewDatabase getInstance is not using double checked locking so it does not have that problem. For double checked locking you check outside of the lock if the instance exists and skip the lock if that is the case. That results in faster execution than always locking since you only need to lock once at the very beginning.

If it was using double checked locking it would look like

public static WebViewDatabase getInstance(Context context) {
    if (mInstance == null) {
        synchronized (WebViewDatabase.class) {
            if (mInstance == null)
                mInstance = new WebViewDatabase(context);
        }
    }
    return mInstance;
}

and mInstance would need to be defined volatile

There is no change regarding synchronization / singletons / double checked locking for Android vs desktop Java

zapl
  • 63,179
  • 10
  • 123
  • 154
  • Ok cheers I get it now, it just says that synchronized is slower but correct, however I don't need to care about speed here because its not like a million threads are trying to access my few singletons so synchronized will do! – Ian Warwick Aug 31 '12 at 13:43
  • 1
    yes, you usually get that warning if you have `if (someInstanceVariable == null) { someInstanceVariable = new XYZ }` without any way to make sure it can't be initialized concurrently. But there are nice other ways to lazily instantiate singletons like this [singleton holder](http://stackoverflow.com/questions/70689/what-is-an-efficient-way-to-implement-a-singleton-pattern-in-java/71683#71683) pattern and more mentioned in that thread / on wikipedia if you look for singleton – zapl Aug 31 '12 at 13:49