Android SharedPreferences 源碼分析

SharedPreferences(下稱SP)在平時開發應用比較多。我應用SP主要用於保存一些影響業務的數值,好比是否第一次激活應用,第一次激活的時間,ABTest分組標誌等等。在開發的應用中,不少與統計數據相關的數值都是用SP進行存儲管理的,使用過程當中的確由於理解不深,出現問題,影響產品決策。所以準確理解使用SP很重要。android

本文參照Android-26的源碼,分析SP的原理和須要注意的問題,主要包括如下幾部分:緩存

  • 分析實現SP功能的類及相互關係
  • SP的內容的讀取、寫入
  • 須要注意的問題

SP的主要類及關係:

SP的功能實現的主要接口和類有:SharedPreferences,Editor,SharedPreferencesImpl,EditorImpl以及ContextImpl,它們之間的關係下圖(UML現學現賣,歡迎指出問題):安全


接口SharedPreferences定義了SP提供SP文件的讀操做,其包含子接口EditorImpl定義了對SP文件寫相關的操做。SharedPreferencesImpl類實現SharedPreferences接口,具體實現SP文件的讀功能以及爲保證讀準確而提供的線程安全等條件,其內部類EditorImpl實現了Editor接口,負責SP文件的實際寫操做。ContextImpl類包含SharedPreferencesImpl,經過方法getSharedPreferences()對外提供SP實例供開發者使用。bash

SP內容的讀寫:

  • 獲取SP實例
@Override
    public SharedPreferences getSharedPreferences(File file, int mode) {
        //檢查讀寫模式
        checkMode(mode);
        //文件級別加密檢查?(待進一步研究)
        if (getApplicationInfo().targetSdkVersion >= android.os.Build.VERSION_CODES.O) {
            if (isCredentialProtectedStorage()
                    && !getSystemService(StorageManager.class).isUserKeyUnlocked(
                            UserHandle.myUserId())
                    && !isBuggy()) {
                throw new IllegalStateException("SharedPreferences in credential encrypted "
                        + "storage are not available until after user is unlocked");
            }
        }
        SharedPreferencesImpl sp;
        synchronized (ContextImpl.class) {
            final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
            sp = cache.get(file);
            if (sp == null) {
                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;
    }
複製代碼

首先經過checkMode()方法檢查文件的讀寫模式,而後針對Android O 及以上版本,進行文件加密檢查,這些檢查都沒有問題後,從緩存中獲取或者建立新的SP實例並返回。先看一下checkMode方法的實現:app

private void checkMode(int mode) {
        if (getApplicationInfo().targetSdkVersion >= Build.VERSION_CODES.N) {
            if ((mode & MODE_WORLD_READABLE) != 0) {
                throw new SecurityException("MODE_WORLD_READABLE no longer supported");
            }
            if ((mode & MODE_WORLD_WRITEABLE) != 0) {
                throw new SecurityException("MODE_WORLD_WRITEABLE no longer supported");
            }
        }
    }
複製代碼

爲安全考慮,Android在N及以上完全禁止MODE_WORLD_READABLE和MODE_WORLD_WRITEABLE模式,checkMode方法中具體作了限制。ide

synchronized (ContextImpl.class) {
            final ArrayMap<File, SharedPreferencesImpl> cache = getSharedPreferencesCacheLocked();
            sp = cache.get(file);
            if (sp == null) {
                sp = new SharedPreferencesImpl(file, mode);
                cache.put(file, sp);
                return sp;
            }
        }
複製代碼

這段代碼是從緩存中根據指定的File獲取SP實例,getSharedPreferencesCacheLocked()方法的實現以下:post

private ArrayMap<File, SharedPreferencesImpl> getSharedPreferencesCacheLocked() {
        if (sSharedPrefsCache == null) {
            sSharedPrefsCache = new ArrayMap<>();
        }

        final String packageName = getPackageName();
        ArrayMap<File, SharedPreferencesImpl> packagePrefs = sSharedPrefsCache.get(packageName);
        if (packagePrefs == null) {
            packagePrefs = new ArrayMap<>();
            sSharedPrefsCache.put(packageName, packagePrefs);
        }

        return packagePrefs;
    }
複製代碼

靜態變量sSharedPrefsCache的定義是一個Key爲String類型,Value的ArrayMap<File, SharedPreferencesImpl>的ArrayMap:性能

/**
     * Map from package name, to preference name, to cached preferences.
     */
private static ArrayMap<String, ArrayMap<File, SharedPreferencesImpl>> sSharedPrefsCache;
複製代碼

它以包名爲key,將每一個應用下的SP實例緩存在一個ArrayMap中。 其實整個獲取SP實例的邏輯很簡單:從緩存中查找,將查找到的對象直接返回,若是沒有就調用SharedPreferencesImpl的構造方法,建立SP實例,添加到緩存中,並返回。ui

SP內容的讀寫:

先看一下SharedPreferencesImpl構造方法的實現:this

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

構造方法主要進行了創建備份文件實例,加載文件到內存的操做,在startLoadFromDisk()方法中,經過同步枷鎖,啓動線程將文件內容加入到內存,這裏提供了一層線程安全保障:

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

具體負責文件內容加載的loadFromDisk()方法:

rivate void loadFromDisk() {
        synchronized (mLock) {
            if (mLoaded) {
                return;
            }
            if (mBackupFile.exists()) {
                mFile.delete();
                mBackupFile.renameTo(mFile);
            }
        }

        // Debugging
        if (mFile.exists() && !mFile.canRead()) {
            Log.w(TAG, "Attempt to read preferences file " + mFile + " without permission");
        }

        Map map = null;
        StructStat stat = null;
        try {
            stat = Os.stat(mFile.getPath());
            if (mFile.canRead()) {
                BufferedInputStream str = null;
                try {
                    str = new BufferedInputStream(
                            new FileInputStream(mFile), 16*1024);
                    map = XmlUtils.readMapXml(str);
                } catch (Exception e) {
                    Log.w(TAG, "Cannot read " + mFile.getAbsolutePath(), e);
                } finally {
                    IoUtils.closeQuietly(str);
                }
            }
        } catch (ErrnoException e) {
            /* ignore */
        }

        synchronized (mLock) {
            mLoaded = true;
            if (map != null) {
                mMap = map;
                mStatTimestamp = stat.st_mtime;
                mStatSize = stat.st_size;
            } else {
                mMap = new HashMap<>();
            }
            mLock.notifyAll();
        }
    }
複製代碼

在這個方法中,首先是加鎖判斷當前狀態,若是已經加載完成,就直接返回,不然會從新設置備份的文件對象。而後使用XmlUtils讀取文件內容,並保存到Map對象mMap中,通知全部正在等待的客戶,文件讀取完成,能夠進行鍵值對的讀寫操做了。這裏須要注意:系統會一次性把SP文件內容讀入到內存並保存在Map對象中。這就是SP文件內容的加載過程。

下面咱們看看從SP文件中獲取值的過程,以getInt()方法爲例:

public int getInt(String key, int defValue) {
        synchronized (mLock) {
            awaitLoadedLocked();
            Integer v = (Integer)mMap.get(key);
            return v != null ? v : defValue;
        }
    }
複製代碼

首先加鎖,避免讀取到錯誤的值,而後調用awaitLoadedLocked(),這個方法的做用是檢測文件內容是否已經讀取到mMap對象中,若是沒有讀取完成,就阻塞,直到接收到讀取完成的通知以後,再從mMap對象中取出value,具體代碼以下:

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) {
            }
        }
    }
複製代碼

能夠看到,若是文件內容讀取完成,getInt()方法會一直阻塞。若是不知道這個細節,很容易致使應用出現ANR的問題。好比場景:進程建立的時候,會進行不少的邏輯處理,在UI進程從SP中獲取value時,若是文件讀取時間長,UI進程被阻塞,容易發生ANR。另外因爲系統是使用Map緩存SP文件中的鍵值對的,基本類型不能做爲value傳入,因此想讀取基本類型的值時,要求傳入一個defaultValue,考慮到運行的安全,避免出現的狀況是,客戶但願獲取一個int值,API返回一個Null的囧像。

SP的寫入操做是由EditorImpl具體實現的。對SP中鍵值對的讀寫操做,分兩步,第一步是由EditorImpl直接更改mMap的值;第二步,將mMap中的鍵值對寫入到文件中保存。這裏須要重點關注兩個方法:apply()和commit(),它們的實現以下:

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;
        }
複製代碼

這兩個方法都作了兩件事情,調用commitToMemory()及時將改動提交到對應的內存區域,而後提交一個寫入文件的任務,等待系統調度。惟一不一樣的是,apply將文件寫入操做放到一個Runnable對象中,等待系統在工做線程中調用。commit方法則是直接在主線程中進行寫入操做。這一點能夠從調度寫入操做的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--; } //使用本次寫入任務提供的Runnable對象 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); } 複製代碼

若是在提交寫入任務時,沒有提供對應的調度Runnable對象,即這次調度任務是經過commit()方法提交,那麼會在當前的線程中進寫操做。這就是爲何提倡使用apply方法的緣由。其實你們根本不須要關注apply和commit兩個方法在數據一致性的差別,這兩個方法對數據的操做都是一致的,惟一區別就是寫入文件時一個另起線程,一個在當前線程。

須要注意的問題:

  • SP文件的讀寫是一次I/O操做,儘可能避開設備資源緊張的場景操做。
  • getValue方法是線程阻塞的
  • apply方法對app性能的影響小,儘可能使用apply方法。
  • 儘可能鏈式調用 Editor對象,由於每次調用SharedPreferencesImpl對象的edit()方法都會建立新的Editor實例
  • 每一個Editor實例包含一個map,包含該Editor實例操做的全部鍵值對。在調用apply或者commit方法以後會首先寫到mMap中。所以,不調用提交方法,那麼操做的鍵值對會被丟棄。
相關文章
相關標籤/搜索