问题描述
纵观<一href="http://developer.android.com/reference/android/content/Shared$p$pferences.html">Shared$p$pferences文档它说:
注:目前这一类不 跨多个进程的支持使用。 这将在以后添加。
所以本身它不会出现是线程安全的。但是,什么样的担保都是由在问候commit()和应用()?
So in and of itself it doesn't appear to be Thread Safe. However, what kind of guarantees are made in regards to commit() and apply()?
例如:
synchronized(uniqueIdLock){
uniqueId = sharedPreferences.getInt("UNIQUE_INCREMENTING_ID", 0);
uniqueId++;
sharedPreferences.edit().putInt("UNIQUE_INCREMENTING_ID", uniqueId).commit();
}
难道是保证了UNIQUEID总是在这种情况下,唯一的?
Would it be guaranteed that the uniqueId was always unique in this case?
如果不是,是否有更好的方法来跟踪一个独特的ID为持续申请?
If not, is there a better way to keep track of a unique id for an application that persists?
推荐答案
进程和线程不同。在Android上的共享preferences实现是线程安全的,但不是过程安全。通常,您的应用程序将在同一个进程中运行的所有,但它可能为你把它配置在AndroidManifest.xml所以,比如说,该服务运行在比,也就是说,活动一个单独的进程。
Processes and Threads are different. The SharedPreferences implementation in Android is thread-safe but not process-safe. Normally your app will run all in the same process, but it's possible for you to configure it in the AndroidManifest.xml so, say, the service runs in a separate process than, say, the activity.
要验证的纤维性安全,请参阅ContextImpl.java的共享preferenceImpl从AOSP。注意:有一个同步的,无论你期望那里是一个。
To verify the thready safety, see the ContextImpl.java's SharedPreferenceImpl from AOSP. Note there's a synchronized wherever you'd expect there to be one.
private static final class SharedPreferencesImpl implements SharedPreferences {
...
public String getString(String key, String defValue) {
synchronized (this) {
String v = (String)mMap.get(key);
return v != null ? v : defValue;
}
}
...
public final class EditorImpl implements Editor {
public Editor putString(String key, String value) {
synchronized (this) {
mModified.put(key, value);
return this;
}
}
...
}
}
不过,对于你的情况的唯一ID看来你还是要同步,你不希望它get和看跌之间切换。
However for your case of the unique id it seems you'd still want a synchronized as you don't want it to change between the get and the put.
这篇关于共享preferences和线程安全的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!