gpt4 book ai didi

android - SharedPreferences 和线程安全

转载 作者:IT王子 更新时间:2023-10-28 23:47:06 31 4
gpt4 key购买 nike

SharedPreferences docs它说:

"Note: currently this class does not support use across multiple processes. This will be added later."

所以它本身似乎不是线程安全的。但是,commit() 和 apply() 做了什么样的保证呢?

例如:

synchronized(uniqueIdLock){
uniqueId = sharedPreferences.getInt("UNIQUE_INCREMENTING_ID", 0);
uniqueId++;
sharedPreferences.edit().putInt("UNIQUE_INCREMENTING_ID", uniqueId).commit();
}

在这种情况下是否可以保证 uniqueId 始终是唯一的?

如果没有,是否有更好的方法来跟踪持续存在的应用程序的唯一 ID?

最佳答案

进程和线程是不同的。 Android 中的 SharedPreferences 实现是线程安全的,但不是进程安全的。通常,您的应用程序将在同一个进程中运行,但您可以在 AndroidManifest.xml 中对其进行配置,例如,服务运行在与 Activity 不同的进程中。

要验证线程安全性,请参阅 AOSP 中的 ContextImpl.java 的 SharedPreferenceImpl。请注意,在您期望的任何地方都有同步。

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 和 put 之间发生变化。

关于android - SharedPreferences 和线程安全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4693387/

31 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com