SharedPreferences

Start

前言

轉(zhuǎn)載
我們知道 SharedPreferences 會(huì)從文件讀取 xml 文件, 并將其以 getXxx/putXxx 的形式提供讀寫服務(wù). 其中涉及到如下幾個(gè)問(wèn)題:

  1. 如何從磁盤讀取配置到內(nèi)存
  2. getXxx 如何從內(nèi)存中獲取配置
  3. 最終配置如何從內(nèi)存回寫到磁盤
  4. 多線程/多進(jìn)程是否會(huì)有問(wèn)題
  5. 最佳實(shí)踐

1. 結(jié)論

  • SharedPreferences 是線程安全的,內(nèi)部由大量 synchronized 關(guān)鍵字保障。
  • SharedPreferences 不是進(jìn)程安全的。
  • 第一次 getSharedPreferences 會(huì)讀取磁盤文件,后續(xù)的 getSharedPreferences 會(huì)從內(nèi)存緩存中獲取。 如果第一次調(diào)用 getSharedPreferences 時(shí)還沒(méi)從磁盤加載完畢就調(diào)用 getXxx/putXxx , 則 getXxx/putXxx 操作會(huì)卡主,直到數(shù)據(jù)從磁盤加載完畢后返回。
  • 所有的 getXxx 都是從內(nèi)存中取的數(shù)據(jù)
  • apply 是同步回寫內(nèi)存,然后把異步回寫磁盤的任務(wù)放到一個(gè)單線程的隊(duì)列中等待調(diào)度。commit 和前者一樣,只不過(guò)要等待異步磁盤任務(wù)結(jié)束后才返回。
  • MODE_MULTI_PROCESS 是在每次 getSharedPreferences 時(shí)檢查磁盤上配置文件上次修改時(shí)間和文件大小, 一旦所有修改則會(huì)重新從磁盤加載文件。 所以并不能保證多進(jìn)程數(shù)據(jù)的實(shí)時(shí)同步。
  • 從 Android N 開始,不再支持 MODE_WORLD_READABLE & MODE_WORLD_WRITEABLE。一旦指定,會(huì)拋異常。

2. 最佳實(shí)踐

  • 不要多進(jìn)程使用,很小幾率會(huì)造成數(shù)據(jù)全部丟失(萬(wàn)分之一), 現(xiàn)象是配置文件被刪除。
  • 不要依賴 MODE_MULTI_PROCESS,這個(gè)標(biāo)記就像 MODE_WORLD_READABLE/MODE_WORLD_WRITEABLE 未來(lái)會(huì)被廢棄。
  • 每次 apply / commit 都會(huì)把全部的數(shù)據(jù)一次性寫入磁盤,所以單個(gè)的配置文件不應(yīng)該過(guò)大, 影響整體性能。

3. 源碼分析

3.1 SharedPreferences 對(duì)象的獲取

一般來(lái)說(shuō)有如下方式:

  1. PreferenceManager.getDefaultSharedPreferences
  2. ContextImpl.getSharedPreferences

我們以上述 [1] 為例來(lái)看看源碼:

// PreferenceManager.java
public static SharedPreferences getDefaultSharedPreferences(Context context) {
    return context.getSharedPreferences(getDefaultSharedPreferencesName(context),
            getDefaultSharedPreferencesMode());
}

可以看到最終也是調(diào)用到了 ContextImpl.getSharedPreferences, 源碼:

// ContextImpl.java
@Override
    public SharedPreferences getSharedPreferences(File file, int mode) {
        SharedPreferencesImpl sp;
        synchronized (ContextImpl.class) {
            final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
            sp = cache.get(file);
            if (sp == null) {
                checkMode(mode);
                if (getApplicationInfo().targetSdkVersion >= android.os.Build.VERSION_CODES.O) {
                    if (isCredentialProtectedStorage()
                            && !getSystemService(UserManager.class)
                                    .isUserUnlockingOrUnlocked(UserHandle.myUserId())) {
                        throw new IllegalStateException("SharedPreferences in credential encrypted "
                                + "storage are not available until after user is unlocked");
                    }
                }
                sp = new SharedPreferencesImpl(file, mode);
                cache.put(file, sp);
                return sp;
            }
        }
        if ((mode & Context.MODE_MULTI_PROCESS) != 0 ||
            getApplicationInfo().targetSdkVersion < android.os.Build.VERSION_CODES.HONEYCOMB) {
            // If somebody else (some other process) changed the prefs
            // file behind our back, we reload it.  This has been the
            // historical (if undocumented) behavior.
            sp.startReloadIfChangedUnexpectedly();
        }
        return sp;
    }

可見 sdk 是先取了緩存,如果緩存未命中,才構(gòu)造對(duì)象。也就是說(shuō),多次 getSharedPreferences 幾乎是沒(méi)有代價(jià)的。 同時(shí), 實(shí)例的構(gòu)造被 synchronized 關(guān)鍵字包裹,因此構(gòu)造過(guò)程是多線程安全的。

3.2 SharedPreferences 的構(gòu)造

第一次構(gòu)建對(duì)象時(shí):

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

有這么幾個(gè)關(guān)鍵信息:

  1. mFile 代表我們磁盤上的配置文件。
  2. mBackupFile 是一個(gè)災(zāi)備文件,用戶寫入失敗時(shí)進(jìn)行恢復(fù),后面會(huì)再說(shuō)。其路徑是 mFile 加后綴 ‘.bak’。
  3. mMap 用于在內(nèi)存中緩存我們的配置數(shù)據(jù), 也就是 getXxx 數(shù)據(jù)的來(lái)源。

還涉及到一個(gè) startLoadFromDisk, 我們來(lái)看看:

// SharedPreferencesImpl.java
    private void startLoadFromDisk() {
        synchronized (mLock) {
            mLoaded = false;
        }
        new Thread("SharedPreferencesImpl-load") {
            public void run() {
                loadFromDisk();
            }
        }.start();
    }

開啟了一個(gè)線程從文件讀取, 其源碼如下:

// SharedPreferencesImpl.java
private void loadFromDisk() {
    synchronized (SharedPreferencesImpl.this) {
        if (mLoaded) {
            return;
        }
        if (mBackupFile.exists()) {
            mFile.delete();
            mBackupFile.renameTo(mFile);
        }
    }

    ... 略去無(wú)關(guān)代碼 ...

    str = new BufferedInputStream(
            new FileInputStream(mFile), 16*1024);
    map = XmlUtils.readMapXml(str);

    synchronized (SharedPreferencesImpl.this) {
        mLoaded = true;
        if (map != null) {
            mMap = map;
            mStatTimestamp = stat.st_mtime;
            mStatSize = stat.st_size;
        } else {
           mMap = new HashMap<>();
        }
        notifyAll();
    }
}

loadFromDisk 這個(gè)函數(shù)很關(guān)鍵。它就是實(shí)際從磁盤讀取配置文件的函數(shù)。 可見, 它做了如下幾件事:

  1. 如果有 ‘災(zāi)備’ 文件,則直接使用災(zāi)備文件回滾。
  2. 把配置從磁盤讀取到內(nèi)存的并保存在 mMap 字段中(看代碼最后 mMap = map)。
  3. 標(biāo)記讀取完成, 這個(gè)字段后面 awaitLoadedLocked 會(huì)用到。 記錄讀取文件的時(shí)間,后面 MODE_MULTI_PROCESS 中會(huì)用到。
  4. 發(fā)一個(gè) notifyAll 通知已經(jīng)讀取完畢, 激活所有等待加載的其他線程。

總結(jié)一下:


從磁盤讀取配置

3.3 getXxx 的流程

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

可見, 所有的 get 操作都是線程安全的。并且 get 僅僅是從內(nèi)存中(mMap) 獲取數(shù)據(jù), 所以無(wú)性能問(wèn)題。

考慮到配置文件的加載是在單獨(dú)的線程中異步進(jìn)行的(參考 ‘SharedPreferences 的構(gòu)造’),所以這里的 awaitLoadedLocked 是在等待配置文件加載完畢。 也就是說(shuō)如果我們第一次構(gòu)造 SharedPreferences 后就立刻調(diào)用 getXxx 方法, 很有可能讀取配置文件的線程還未完成, 所以這里要等待該線程做完相應(yīng)的加載工作。

來(lái)看看 awaitLoadedLocked 的源碼:

// SharedPreferencesImpl.java 
  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) {
            }
        }
        if (mThrowable != null) {
            throw new IllegalStateException(mThrowable);
        }
    }

很明顯,如果加載還未完成(mLoaded == false),getXxx 會(huì)卡在 awaitLoadedLocked,一旦加載配置文件的線程工作完畢, 則這個(gè)加載線程會(huì)通過(guò) notifyAll 會(huì)通知所有在 awaitLoadedLocked 中等待的線程,getXxx 就能夠返回了。不過(guò)大部分情況下,mLoaded == true。這樣的話 awaitLoadedLocked 會(huì)直接返回。

3.4 putXxx 的流程

setget 稍微麻煩一點(diǎn)兒,因?yàn)樯婕暗?EditorMemoryCommitResult 對(duì)象。

先來(lái)看看 edit() 方法的實(shí)現(xiàn):

// SharedPreferencesImpl.java
public Editor edit() {
    // TODO: remove the need to call awaitLoadedLocked() when
    // requesting an editor.  will require some work on the
    // Editor, but then we should be able to do:
    //
    //      context.getSharedPreferences(..).edit().putString(..).apply()
    //
    // ... all without blocking.
    synchronized (this) {
        awaitLoadedLocked();
    }

    return new EditorImpl();
}

Editor

Editor 沒(méi)有構(gòu)造函數(shù),只有兩個(gè)屬性被初始化:

// SharedPreferencesImpl.java
public final class EditorImpl implements Editor {
    private final Object mEditorLock = new Object();

    @GuardedBy("mEditorLock")
    private final Map<String, Object> mModified = new HashMap<>();

    @GuardedBy("mEditorLock")
    private boolean mClear = false;

    ... 略去方法定義 ...
    public Editor putString(String key, @Nullable String value) { ... }
    public boolean commit() { ... }
    ...
}

mModified 是我們每次 putXxx 后所改變的配置項(xiàng)。
mClear 標(biāo)識(shí)要清空配置項(xiàng), 但是只清了 SharedPreferences.mMap 。

edit() 會(huì)保障配置已從磁盤讀取完畢,然后僅僅創(chuàng)建了一個(gè)對(duì)象。接下來(lái)看看 putXxx 的真身:

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

很簡(jiǎn)單,僅僅是把我們?cè)O(shè)置的配置項(xiàng)放到了 mModified 屬性里保存。等到 apply 或者 commit 的時(shí)候回寫到內(nèi)存和磁盤。咱們分別來(lái)看看。

apply

apply 是各種 ‘最佳實(shí)踐’ 推薦的方式,那么它到底是怎么異步工作的呢?我們來(lái)看個(gè)究竟:

// SharedPreferencesImpl.java
public void apply() {
    final MemoryCommitResult mcr = commitToMemory();
    final Runnable awaitCommit = new Runnable() {
            public void run() {
                try {
                    mcr.writtenToDiskLatch.await();
                } catch (InterruptedException ignored) {
                }
            }
        };

    QueuedWork.add(awaitCommit);

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

    SharedPreferencesImpl.this.enqueueDiskWrite(mcr, postWriteRunnable);

    // Okay to notify the listeners before it&#039;s hit disk
    // because the listeners should always get the same
    // SharedPreferences instance back, which has the
    // changes reflected in memory.
    notifyListeners(mcr);
}

可以看出大致的脈絡(luò):

  1. commitToMemory 應(yīng)該是把修改的配置項(xiàng)回寫到內(nèi)存。
  2. QueuedWork.add(awaitCommit) 貌似沒(méi)什么卵用。
  3. SharedPreferencesImpl.this.enqueueDiskWrite 把配置項(xiàng)加入到一個(gè)異步隊(duì)列中,等待調(diào)度。

我們來(lái)看看 commitToMemory 的實(shí)現(xiàn)(略去大量無(wú)關(guān)代碼):

// SharedPreferencesImpl.java
private MemoryCommitResult commitToMemory() {
    MemoryCommitResult mcr = new MemoryCommitResult();
    synchronized (SharedPreferencesImpl.this) {

        ... 略去無(wú)關(guān) ...

        mapToWriteToDisk = mMap;
                mDiskWritesInFlight++;

                boolean hasListeners = mListeners.size() > 0;
                if (hasListeners) {
                    keysModified = new ArrayList<String>();
                    listeners = new HashSet<OnSharedPreferenceChangeListener>(mListeners.keySet());
                }

                synchronized (mEditorLock) {
                    boolean changesMade = false;

                    if (mClear) {
                        if (!mapToWriteToDisk.isEmpty()) {
                            changesMade = true;
                            mapToWriteToDisk.clear();
                        }
                        mClear = false;
                    }

                    for (Map.Entry<String, Object> e : mModified.entrySet()) {
                        String k = e.getKey();
                        Object v = e.getValue();
                        // "this" is the magic value for a removal mutation. In addition,
                        // setting a value to "null" for a given key is specified to be
                        // equivalent to calling remove on that key.
                        if (v == this || v == null) {
                            if (!mapToWriteToDisk.containsKey(k)) {
                                continue;
                            }
                            mapToWriteToDisk.remove(k);
                        } else {
                            if (mapToWriteToDisk.containsKey(k)) {
                                Object existingValue = mapToWriteToDisk.get(k);
                                if (existingValue != null && existingValue.equals(v)) {
                                    continue;
                                }
                            }
                            mapToWriteToDisk.put(k, v);
                        }

                        changesMade = true;
                        if (hasListeners) {
                            keysModified.add(k);
                        }
                    }

                    mModified.clear();

                    if (changesMade) {
                        mCurrentMemoryStateGeneration++;
                    }

                    memoryStateGeneration = mCurrentMemoryStateGeneration;
                }
            }
            return new MemoryCommitResult(memoryStateGeneration, keysModified, listeners,
                    mapToWriteToDisk);
        }
}

總結(jié)來(lái)說(shuō)就兩件事:

  1. Editor.mModified 中的配置項(xiàng)回寫到 SharedPreferences.mMap 中,完成了內(nèi)存的同步。
  2. 把 SharedPreferences.mMap 保存在了 mcr.mapToWriteToDisk 中。而后者就是即將要回寫到磁盤的數(shù)據(jù)源。

我們?cè)賮?lái)回頭看看 apply 方法:

// SharedPreferencesImpl.java
public void apply() {
    final MemoryCommitResult mcr = commitToMemory();

    ... 略無(wú)關(guān) ...

    SharedPreferencesImpl.this.enqueueDiskWrite(mcr, postWriteRunnable);
}
  • commitToMemory 完成了內(nèi)存的同步回寫
  • enqueueDiskWrite 完成了硬盤的異步回寫, 我們接下來(lái)具體看看 enqueueDiskWrite
// SharedPreferencesImpl.java
private void enqueueDiskWrite(final MemoryCommitResult mcr,
                                final Runnable postWriteRunnable) {
    final Runnable writeToDiskRunnable = new Runnable() {
            public void run() {
                synchronized (mWritingToDiskLock) {
                    writeToFile(mcr);
                }

                ...
            }
        };

    ...

    QueuedWork.singleThreadExecutor().execute(writeToDiskRunnable);
}

QueuedWork.singleThreadExecutor 實(shí)際上就是 ‘一個(gè)線程的線程池’, 如下:

// QueuedWork.java
public static ExecutorService singleThreadExecutor() {
    synchronized (QueuedWork.class) {
        if (sSingleThreadExecutor == null) {
            // TODO: can we give this single thread a thread name?
            sSingleThreadExecutor = Executors.newSingleThreadExecutor();
        }
        return sSingleThreadExecutor;
    }
}

回到 enqueueDiskWrite 中,這里還有一個(gè)重要的函數(shù)叫做 writeToFile:

writeToFile

// SharedPreferencesImpl.java
private void writeToFile(MemoryCommitResult mcr) {
    // Rename the current file so it may be used as a backup during the next read
    if (mFile.exists()) {
        if (!mBackupFile.exists()) {
            if (!mFile.renameTo(mBackupFile)) {
                return;
            }
        } else {
            mFile.delete();
        }
    }

    // Attempt to write the file, delete the backup and return true as atomically as
    // possible.  If any exception occurs, delete the new file; next time we will restore
    // from the backup.
    try {
        FileOutputStream str = createFileOutputStream(mFile);
        XmlUtils.writeMapXml(mcr.mapToWriteToDisk, str);
        ContextImpl.setFilePermissionsFromMode(mFile.getPath(), mMode, 0);
        try {
            final StructStat stat = Os.stat(mFile.getPath());
                mStatTimestamp = stat.st_mtime;
                mStatSize = stat.st_size;
        }
        // Writing was successful, delete the backup file if there is one.
        mBackupFile.delete();
        return;
    }

    // Clean up an unsuccessfully written file
    mFile.delete();
}

代碼大致分為三個(gè)過(guò)程:

  1. 先把已存在的老的配置文件重命名(加 ‘.bak’ 后綴), 然后刪除老的配置文件。這相當(dāng)于做了災(zāi)備。
  2. mFile 中一次性寫入所有配置項(xiàng)。即 mcr.mapToWriteToDisk(這就是 commitToMemory 所說(shuō)的保存了所有配置項(xiàng)的字段) 一次性寫入到磁盤。如果寫入成功則刪除災(zāi)備文件,同時(shí)記錄了這次同步的時(shí)間。
  3. 如果上述過(guò)程 [2] 失敗,則刪除這個(gè)半成品的配置文件。

好了, 我們來(lái)總結(jié)一下 apply:

  1. 通過(guò) commitToMemory 將修改的配置項(xiàng)同步回寫到內(nèi)存 SharedPreferences.mMap 中。此時(shí),任何的 getXxx 都可以獲取到最新數(shù)據(jù)了。
  2. 通過(guò) enqueueDiskWrite 調(diào)用 writeToFile 將所有配置項(xiàng)一次性異步回寫到磁盤, 這是一個(gè)單線程的線程池。

時(shí)序圖:

apply 時(shí)序圖

commit

看過(guò)了 apply 再看 commit 就非常容易了。

// SharedPreferencesImpl.java
public boolean commit() {
    MemoryCommitResult mcr = commitToMemory();
    SharedPreferencesImpl.this.enqueueDiskWrite(
        mcr, null /* sync write on this thread okay */);
    try {
        mcr.writtenToDiskLatch.await();
    } catch (InterruptedException e) {
        return false;
    }
    notifyListeners(mcr);
    return mcr.writeToDiskResult;
}

時(shí)序圖:

commit 時(shí)序圖

只需關(guān)注最后一條 ‘等待異步任務(wù)返回’ 的線,對(duì)比 apply 的時(shí)序圖, 一眼就看出差別。

registerOnSharedPreferenceChangeListener

最后需要提一下的就是 listener:

  • 對(duì)于 apply,listener 回調(diào)時(shí)內(nèi)存已經(jīng)完成同步, 但是異步磁盤任務(wù)不保證是否完成。
  • 對(duì)于 commit, listener 回調(diào)時(shí)內(nèi)存和磁盤都已經(jīng)同步完畢。

申明:開始的圖片來(lái)源網(wǎng)絡(luò),侵刪

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容