Reputation: 119
I have a public static method in one of my classes for my app which saves a number to SharedPreferences after incrementing it. For example if the preference value is a long equal to 1, the method will read the preference of 1 into a long variable, then increment it to 2, and put that long back into the preference.
Do I ever have to worry about synchronization issues? At first I don't think so, because my application is not multithreaded right? It uses Android Services, but I think that is only single threaded as well.
Upvotes: 3
Views: 4937
Reputation: 10009
Java has a solution for the Synchronization
by simply implement the method in a synchronized
structure as the following"
public synchronized void modifyPreferences(long input)
{
//Do some stuff
}
The SharefPreferences
documentation says about using apply()
vs commit()
for saving your edits:
Using apply(), Note that when two editors are modifying preferences at the same time, the last one to call apply wins.
Unlike commit(), which writes its preferences out to persistent storage synchronously, apply() commits its changes to the in-memory SharedPreferences immediately but starts an asynchronous commit to disk and you won't be notified of any failures. If another editor on this SharedPreferences does a regular commit() while a apply() is still outstanding, the commit() will block until all async commits are completed as well as the commit itself.
I hope this helps.
Upvotes: 7