I’m not sure if I actually need this right now but if my app ever expands I could see the possibility. I basically have a wrapper around SharedPreferences that pulls a few values out of SharedPreferences and bundles them into an object. It also takes an object and uses it to update preferences. I wanted to make it thread-safe, but I wanted to try it with a Semaphore. My SharedPreferences wrapper will get a reference to the class below from getSyncedPrefManager(). It will then call aquireLock() followed by getPref(), do its work and then call releaseLock(). Does this look like something that would work or am I way off base?
public class SyncedPreferenceManager {
private final static SyncedPreferenceManager me =
new SyncedPreferenceManager();
private SharedPreferences prefs;
private static Semaphore mutex;
public static SyncedPreferenceManager getSyncedPrefManager(){
return me;
}
private SyncedPreferenceManager(){
mutex = new Semaphore(1, true);
}
public SharedPreferences getPref(Context caller){
if(prefs == null)
prefs = PreferenceManager.getDefaultSharedPreferences(caller);
return prefs;
}
public boolean aquireLock(){
try {
mutex.acquire();
} catch (InterruptedException e) {
return false;
}
return true;
}
public boolean releaseLock(){
mutex.release();
return true;
}
}
You might not like this answer.
You are not using the right system here. SharedPreferences is for storing simple preferences. Just because you can do this does not mean you should. You’re basically trying to make SharedPreferences into something its not. You can add all this fancy locking but it won’t stop someone from coming in underneath this later and accidentally blowing it up.
If you find yourself needing these feature in earnest, you should look at just using sqlite directly. There is little doubt you could add synchronization to SharedPreferences (and I am sure it is safe to some degree as it is already designed with a transaction/commit model) but it seems to me like reinventing the wheel.