SharedPreferemces在低版本上是支撑多进程的,但其多进程操作不安全,后续不再支撑。经过前文咱们知道,能够经过

SharedPreferences sharedPreferences = context.getSharedPreferences("hello",MODE_PRIVATE);

来获取SharedPreferences接口的完成类SharedPreferencesImpl的实例目标,getSharedPreferences方法原型如下:

@Override
public SharedPreferences getSharedPreferences(String name, int mode) {
  // ... 省掉内容
}

其需求两个参数,String类型的name,其取值为所要拜访的xml文件名称,int型的mode,取值为SharedPreferences文件的拜访方式,SharedPreferences拜访形式有5种,分别为:

  • MODE_PRIVATE:默认操作形式,表明所拜访的文件为运用私有文件,只有当时运用才干拜访,该形式下,写入的内容会覆盖原文件的内容
  • MODE_APPEND:检查文件是否存在,存在就往文件追加内容,不然就创立新文件.
  • MODE_WORLD_READABLE:表明所创立的文件,一切运用都可读,已弃用
  • MODE_WORLD_WRITEABLE:表明所创立的文件,一切运用都可写,已弃用
  • MODE_MULTI_PROCESS:表明所创立的文件,支撑多进程读写,已弃用

从SharedPreferences的创立形式来看,理论上来讲,SharedPreferences是支撑多进程的,可是跟着体系版本迭代,跨进程相关的形式根本都被弃用了,主要原因在于SharedPreferences供给的这些拜访形式多进程环境下不安全。

一切运用可读写,不安全

针对MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE形式而言,其过于开放,没有合理机制校验操作方信息,所以必然是不安全的。

在Android 7.0以上,如果咱们运用MODE_WORLD_READABLE或MODE_WORLD_WRITEABLE创立SharedPreferences会直接抛出异常,相关代码如下所示:

面试问题002-SharedPreferences支持多进程调用吗,多进程安全吗?

MODE_MULTI_PROCESS,不可靠,不安全

在Android源码中,关于MODE_MULTI_PROCESS的注释如下:

SharedPreference loading flag: when set, the file on disk will be checked for modification even if the shared preferences instance is already loaded in this process. This behavior is sometimes desired in cases where the application has multiple processes, all writing to the same SharedPreferences file. Generally there are better forms of communication between processes, though. This was the legacy (but undocumented) behavior in and before Gingerbread (Android 2.3) and this flag is implied when targeting such releases. For applications targeting SDK versions greater than Android 2.3, this flag must be explicitly set if desired. Deprecated MODE_MULTI_PROCESS does not work reliably in some versions of Android, and furthermore does not provide any mechanism for reconciling concurrent modifications across processes. Applications should not attempt to use it. Instead, they should use an explicit cross-process data management approach such as ContentProvider. See Also: getSharedPreferences

从这段注释咱们能够显着看出MODE_MULTI_PROCESS在有些Android版本上是不可靠的,而且并没有供给任何协调进程间并发修改的机制,所以MODE_MULTI_PROCESS在跨进程同享数据方面也不可靠,不安全。

从MODE_MULTI_PROCESS形式的代码逻辑部分也能够看出其并不具备处理并发的才能,MODE_MULTI_PROCESS作业的源码如下所示:

面试问题002-SharedPreferences支持多进程调用吗,多进程安全吗?

能够看出针对MODE_MULTI_PROCESS形式而言,仅仅要求获取SharedPreferences时,从头从文件加载数据罢了。

那么怎样运用SharedPreferences在进程间同享数据呢?上文源码注释中也有说明,运用ContentProvider包裹SharedPreferences即可,当然咱们也能够经过文件锁,MMKV等其他方式来完成目标。

总结

面试问题002-SharedPreferences支持多进程调用吗,多进程安全吗?