SharedPreferences总结

前言:

SharedPreferences很早就用过,但也只限于会用,隔了一段时间再用发现有点生疏,还是要去网上找用法,对其运行原理和不同方法间的区别也知之甚少,决定写一篇文章来总结一下,加深下印象和理解。

概述:

SharedPreferences是Android提供的几种常用的数据存储解决方案之一,应用可以通过它来访问和修改一些他们所关注的数据,常被用来存储少量的、格式简单的配置信息。其本质上是以键值(key-value)对的方式把用户设置信息存储在xml文件中的一种轻量级的数据存储方法。个人更愿意把它理解为是对文件数据存储方法的一个封装,开发者可以通过这个类更简便、更高效的去完成轻量级数据的存储。下面将围绕该存储方式所涉及到的两个主要类——SharedPreferences和SharedPreferencesImpl来逐步深入学习。

正文

SharedPreferences

从SharedPreferences的源码来看,SharedPreferences其实是一个接口类,里面定义了一系列对数据访问、修改和监听数据变化的方法。在数据访问方面,开发者可以通过其提供的getXXX方法来访问其存储的数据,通过contains方法来查询是否存储了你所关注的数据。在数据修改方面,SharedPreferences内部定义了一个内部类Editor,用来对数据进行添加(putXXX)、移除(remove,clear)、提交(commit,apply)等修改操作。SharedPreferences还提供了监听数据变化的监听器(OnSharedPreferenceChangeListener),开发者可以通过registerOnSharedPreferenceChangeListener方法来注册监听器,时刻关注感兴趣数据的变化,当不再需要监听时,可以通过unregisterOnSharedPreferenceChangeListener方法来注销监听器释放相关的资源。

SharedPreferencesImpl

SharedPreferencesImpl作为SharedPreferences的实现类,其内部结构大致跟SharedPreferences类差不多。下面对其内部源码进行逐一分解。

首先,来看一下SharedPreferencesImpl的构造方法:

  SharedPreferencesImpl(File file, int mode) {
      mFile = file;
      mBackupFile = makeBackupFile(file);
      mMode = mode;
      mLoaded = false;
      mMap = null;
      startLoadFromDisk();
  }

  private void loadFromDisk() {
      ...
      str = new BufferedInputStream(
                new FileInputStream(mFile), 16*1024);
      map = XmlUtils.readMapXml(str);
      ...
  }

在SharedPreferencesImpl的构造方法中一共要传递两个参数,file和mode。其中,file是SharedPreferences用来存储数据的文件,mode决定了可以对这个file文件所做的操作。SharedPreferencesImpl首先会对file文件进行一个备份和相关的一些初始化,在构造函数的最后从传递过来的xml文件中读取数据并存储到内部的HashMap以便后续的操作。这里我们能很直观的看出SharedPreferences其本质就是对xml文件的操作,是对文件数据存储的一个封装。

其次,看一下SharedPreferencesImpl是如何实现读取数据的。以getString方法为例,可以看到getXXX方法的实现都比较简单,最外层是一个同步锁,内层awaitLoadedLocked相当于一个线程锁,如果数据加载没有完成就会一直死循环等待加载完成,通过这两个锁来保证数据读取的线程安全和准确性。这两个锁都顺利执行完就会从之前加载好的HashMap里面读取出对应key的值,如果值为空则返回之前约定的缺省值。

  @Nullable
  public String getString(String key, @Nullable String defValue) {
      synchronized (mLock) {
          awaitLoadedLocked();
          String v = (String)mMap.get(key);
          return v != null ? v : defValue;
      }
  }

  private void awaitLoadedLocked() {
      if (!mLoaded) {
          // Raise an explicit StrictMode onReadFromDisk for this
          // thread, since the real read will be in a different
          // thread and otherwise ignored by StrictMode.
          BlockGuard.getThreadPolicy().onReadFromDisk();
      }
      while (!mLoaded) {
          try {
              mLock.wait();
          } catch (InterruptedException unused) {
          }
      }
  }

再次,看一下数据是如何修改的。与SharedPreferences代码结构类似,SharedPreferencesImpl内部也实现了一个Editor的实现类EditorImpl,用来提供相应的数据存储、修改和删除等操作。还是以putString方法为例,发现与getString相比,putString的实现更为简单,紧使用了一个同步锁来保证线程安全,如果校验没有被锁的情况下就会把数据直接写入HashMap中。

  public Editor putString(String key, @Nullable String value) {
      synchronized (mLock) {
          mModified.put(key, value);
          return this;
      }
  }

使用putXXX或是remove等方法操作的都是读取到HashMap中的数据,只有调用了EditorImpl中的apply或是commit方法才会真正的把值写入xml文件永久的保存。 接下来通过源码来分析一下这两个方法的区别。

    public void apply() {
        final long startTime = System.currentTimeMillis();
        final MemoryCommitResult mcr = commitToMemory();
        final Runnable awaitCommit = new Runnable() {
                public void run() {
                    try {
                        mcr.writtenToDiskLatch.await();
                    } catch (InterruptedException ignored) {
                    }

                    if (DEBUG && mcr.wasWritten) {
                        Log.d(TAG, mFile.getName() + ":" + mcr.memoryStateGeneration
                                + " applied after " + (System.currentTimeMillis() - startTime)
                                + " ms");
                    }
                }
            };

        QueuedWork.addFinisher(awaitCommit);

        Runnable postWriteRunnable = new Runnable() {
                public void run() {
                    awaitCommit.run();
                    QueuedWork.removeFinisher(awaitCommit);
                }
            };

        SharedPreferencesImpl.this.enqueueDiskWrite(mcr, postWriteRunnable);

        // Okay to notify the listeners before it's hit disk
        // because the listeners should always get the same
        // SharedPreferences instance back, which has the
        // changes reflected in memory.
        notifyListeners(mcr);
    }
    
    public boolean commit() {
        long startTime = 0;

        if (DEBUG) {
            startTime = System.currentTimeMillis();
        }

        MemoryCommitResult mcr = commitToMemory();

        SharedPreferencesImpl.this.enqueueDiskWrite(
            mcr, null /* sync write on this thread okay */);
        try {
            mcr.writtenToDiskLatch.await();
        } catch (InterruptedException e) {
            return false;
        } finally {
            if (DEBUG) {
                Log.d(TAG, mFile.getName() + ":" + mcr.memoryStateGeneration
                        + " committed after " + (System.currentTimeMillis() - startTime)
                        + " ms");
            }
        }
        notifyListeners(mcr);
        return mcr.writeToDiskResult;
    }

从源码上看,可以明显的看出有两个不同点:
1、commit方法有返回值,而apply方法没有。
2、apply方法在执行 SharedPreferencesImpl的enqueueDiskWrite方法进行排队时多传递了一个Runnable(postWriteRunnable)参数,这个参数传与不传有什么区别呢,我们接着来看enqueueDiskWrite方法的实现。
/**
* Enqueue an already-committed-to-memory result to be written
* to disk.
*
* They will be written to disk one-at-a-time in the order
* that they're enqueued.
*
* @param postWriteRunnable if non-null, we're being called
* from apply() and this is the runnable to run after
* the write proceeds. if null (from a regular commit()),
* then we're allowed to do this disk write on the main
* thread (which in addition to reducing allocations and
* creating a background thread, this has the advantage that
* we catch them in userdebug StrictMode reports to convert
* them where possible to apply() ...)
*/

private void enqueueDiskWrite(final MemoryCommitResult mcr,
                              final Runnable postWriteRunnable) {
    final boolean isFromSyncCommit = (postWriteRunnable == null);

    final Runnable writeToDiskRunnable = new Runnable() {
            public void run() {
                synchronized (mWritingToDiskLock) {
                    writeToFile(mcr, isFromSyncCommit);
                }
                synchronized (mLock) {
                    mDiskWritesInFlight--;
                }
                if (postWriteRunnable != null) {
                    postWriteRunnable.run();
                }
            }
        };

    // Typical #commit() path with fewer allocations, doing a write on
    // the current thread.
    if (isFromSyncCommit) {
        boolean wasEmpty = false;
        synchronized (mLock) {
            wasEmpty = mDiskWritesInFlight == 1;
        }
        if (wasEmpty) {
            writeToDiskRunnable.run();
            return;
        }
    }

    QueuedWork.queue(writeToDiskRunnable, !isFromSyncCommit);
}

从enqueueDiskWrite源码可以看出,如果通过commit方法提交修改,postWriteRunnable 不为空,在执行enqueueDiskWrite方法时会直接执行writeToDiskRunnable把数据写入磁盘。而通过apply方法提交的修改请求,则会把writeToDiskRunnable加入到排队序列中顺序执行。

小结:
通过上面的分析,通过commit和apply两种方法提交数据修改有两点不同:
1、commit方法有返回值,而apply方法没有。使用commit方法能够明确的知道你的提交是否成功,而在不关心提交结果的情况下可以使用apply方法。
2、commit方法是同步的,apply方法是异步的。在多个commit方法并发执行的时候,他们会等待正在处理的commit方法保存到磁盘后再操作,降低了效率。而apply不关心提交是否成功,不必等待返回结果,他们只需要把提交写到内存然后异步的顺序执行,最后提交的磁盘。

在大多数情况下,我们对commit的成功与否并不感兴趣,而且在数据并发处理时基于上述原因使用commit要比apply效率低,所以推荐使用apply。

总结

本文通过解读Android 8.0源码分析了SharedPreferences是如何实现数据的读写操作以及两种提交修改方法的区别和优缺点。关于SharedPreferences的具体使用方法可以参考Android 浅析 SharedPreferences (一) 使用

参考文献:

https://developer.android.google.cn/reference/android/content/SharedPreferences.html
http://androidxref.com/8.0.0_r4/xref/frameworks/base/core/java/android/content/SharedPreferences.java
http://androidxref.com/8.0.0_r4/xref/frameworks/base/core/java/android/app/SharedPreferencesImpl.java

猜你喜欢

转载自blog.csdn.net/lj19851227/article/details/79083069
今日推荐