问题
I have a helper class for dealing with the default shared preferences. I retrieve the preferences once and I wrap all the SP methods I need, providing the same cached instance. It goes like:
public final class AccessPreferences {
private static SharedPreferences prefs; // cache
private static SharedPreferences getPrefs(Context ctx) {
// synchronized is really needed or volatile is all I need (visibility)
SharedPreferences result = prefs;
if (result == null)
synchronized (AccessPreferences.class) {
result = prefs;
if (result == null) {
result = prefs = PreferenceManager
.getDefaultSharedPreferences(ctx);
}
}
return result;
}
public static boolean contains(Context ctx, String key) {
if (key == null)
throw new NullPointerException("Null keys are not permitted");
return getPrefs(ctx).contains(key);
}
//etc
}
I have two questions I want to be absolutely sure about:
- Do I need synchronization as I do or a simple volatile would suffice ? Of course this helper class is accessed by different threads (the UI, Intent services etc).
- Do I need to call
ctx.getApplicationContext()
or not when retrieving the shared preferences ?
I am interested in Froyo and up
回答1:
Use synchronization, but I would suggest using something like a ReentrantLock (http://docs.oracle.com/javase/7/docs/api/java/util/concurrent/locks/ReentrantLock.html) instead of "synchronized". It is generally more performant.
Any context will work, so long as it's not null of course. I would just use the application context here, which will save your callers from having to supply it. Expose a static reference to it, as seen here: Static way to get 'Context' on Android?
来源:https://stackoverflow.com/questions/20846812/getdefaultsharedpreferencescontext-any-context