Reputation: 4784
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
Upvotes: 0
Views: 3262
Reputation: 63955
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
Upvotes: 5