简体   繁体   中英

The right way to do lazy initialization of singletons in Android?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM