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;
}
}