天天看點

SharedPreferences的全面解析

本文主要參考 :

深入了解Android中的SharedPreferences

SharedPreferences的apply和Commit方法的那些坑

可能導緻ANR的情況

  • 在UI線程中調用getXXX 或 edit()方法 (第一次調用getSharedPreferences()後)
  • 用apply方法送出修改,當Activity的onPause/onStop等方法被調用時
  • 在UI線程調用commit方法

導緻ANR最主要原因

I/O瓶頸,如果讀寫操作慢,就有可能導緻ANR。

建議:sp隻适合輕量級資料的存儲,适合少量資料的持久化。

注意點

  • commit的寫操作是在調用線程中執行的,而apply内部是用一個單線程的線程池實作的。
  • SharedPreferences每次寫入都是整個檔案重新寫入,不是增量寫入

具體分析

對于同一個name,當第一次調用getSharedPreferences()時,最終會建立一個SharedPreferencesImpl對象。

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

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

    private 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), *);
                    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_mtim;
                mStatSize = stat.st_size;
            } else {
                mMap = new HashMap<>();
            }
            mLock.notifyAll();
        }
    }
           

它會開啟一個子線程,然後去把指定的SharedPreferences檔案中的鍵值對全部讀取出來,存放在一個Map中。

如果我們在UI線程調用getString()方法,調用getString時那個SharedPreferencesImpl構造方法開啟的子線程可能還沒執行完(比如檔案比較大時全部讀取會比較久),這時getString當然還不能擷取到相應的值,必須阻塞到那個子線程讀取完為止。

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

顯然這個awaitLoadedLocked方法就是用來等this這個鎖的,在loadFromDiskLocked方法的最後我們也可以看到它調用了notifyAll方法,這時如果getString之前阻塞了就會被喚醒。那麼現在這裡有一個問題,我們的getString是寫在UI線程中,如果那個getString被阻塞太久了,比如60s,這時就會出現ANR,是以要根據具體情況考慮是否需要把SharedPreferences的讀寫放在子線程中。

SharedPreferences的初始化和讀取比較簡單,寫操作就相對複雜了點,我們知道寫一個SharedPreferences檔案都是先要調用edit方法擷取到一個Editor對象:

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 (mLock) {
            awaitLoadedLocked();
        }

        return new EditorImpl();
    }
           

edit()方法也類似會導緻ANR問題。

其實拿到的是一個EditorImpl對象,它是SharedPreferencesImpl的内部類:

public final class EditorImpl implements Editor {
        private final Object mLock = new Object();

        @GuardedBy("mLock")
        private final Map<String, Object> mModified = Maps.newHashMap();

        @GuardedBy("mLock")
        private boolean mClear = false;
        .......
}
           

可以看到它有一個Map對象mModified,用來儲存“髒資料”,也就是你每次put的時候其實是把那個鍵值對放到這個mModified 中,最後調用apply或者commit才會真正把資料寫入檔案中,比如看putString:

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

EditorImpl類的關鍵就是apply和commit,不過它們有一些差別,先看commit方法:

public boolean commit() {
            long startTime = ;

            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,再調用enqueueDiskWrite,commitToMemory就是産生一個“合适”的MemoryCommitResult對象mcr,然後調用enqueueDiskWrite時需要把這個對象傳進去,commitToMemory方法:

// Returns true if any changes were made
        private MemoryCommitResult commitToMemory() {
            long memoryStateGeneration;
            List<String> keysModified = null;
            Set<OnSharedPreferenceChangeListener> listeners = null;
            Map<String, Object> mapToWriteToDisk;

            synchronized (SharedPreferencesImpl.this.mLock) {
                // We optimistically don't make a deep copy until
                // a memory commit comes in when we're already
                // writing to disk.
                if (mDiskWritesInFlight > ) {
                    // We can't modify our mMap as a currently
                    // in-flight write owns it.  Clone it before
                    // modifying it.
                    // noinspection unchecked
                    mMap = new HashMap<String, Object>(mMap);
                }
                mapToWriteToDisk = mMap;
                mDiskWritesInFlight++;

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

                synchronized (mLock) {
                    boolean changesMade = false;

                    if (mClear) {
                        if (!mMap.isEmpty()) {
                            changesMade = true;
                            mMap.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 (!mMap.containsKey(k)) {
                                continue;
                            }
                            mMap.remove(k);
                        } else {
                            if (mMap.containsKey(k)) {
                                Object existingValue = mMap.get(k);
                                if (existingValue != null && existingValue.equals(v)) {
                                    continue;
                                }
                            }
                            mMap.put(k, v);
                        }

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

                    mModified.clear();

                    if (changesMade) {
                        mCurrentMemoryStateGeneration++;
                    }

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

這裡需要弄清楚兩個對象mMap和mModified,mMap是存放目前SharedPreferences檔案中的鍵值對,而mModified是存放此時edit時put進去的鍵值對。mDiskWritesInFlight表示正在等待寫的操作數量。可以看到這個方法中首先處理了clear标志,它調用的是mMap.clear(),然後再周遊mModified将新的鍵值對put進mMap,也就是說在一次commit事務中,如果同時put一些鍵值對和調用clear,那麼clear掉的隻是之前的鍵值對,這次put進去的鍵值對還是會被寫入的。周遊mModified時,需要處理一個特殊情況,就是如果一個鍵值對的value是this(SharedPreferencesImpl)或者是null那麼表示将此鍵值對删除,這個在remove方法中可以看到:

public Editor remove(String key) {
            synchronized (mLock) {
                mModified.put(key, this);
                return this;
            }
}
           

commit接下來就是調用enqueueDiskWrite方法:

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 == ;
            }
            if (wasEmpty) {
                writeToDiskRunnable.run();
                return;
            }
        }

        QueuedWork.queue(writeToDiskRunnable, !isFromSyncCommit);
}
           

先定義一個Runnable,注意實作Runnable與繼承Thread的差別,Runnable表示一個任務,不一定要在子線程中執行,一般優先考慮使用Runnable。這個Runnable中先調用writeToFile進行寫操作,寫操作需要先獲得mWritingToDiskLock,也就是寫鎖。然後執行mDiskWritesInFlight–,表示正在等待寫的操作減少1。最後判斷postWriteRunnable是否為null,調用commit時它為null,而調用apply時它不為null。

Runnable定義完,就判斷這次是commit還是apply,如果是commit,即isFromSyncCommit為true,而且有1個寫操作需要執行,那麼就調用writeToDiskRunnable.run(),注意這個調用是在目前線程中進行的。如果不是commit,那就是apply,這時調用QueuedWork.singleThreadExecutor().execute(writeToDiskRunnable),這個QueuedWork類其實很簡單,裡面有一個SingleThreadExecutor,用于異步執行這個writeToDiskRunnable。commit的寫操作是在調用線程中執行的,而apply内部是用一個單線程的線程池實作的,是以寫操作是在子線程中執行的。

說一下那個mBackupFile,SharedPreferences在寫入時會先把之前的xml檔案改成名成一個備份檔案,然後再将要寫入的資料寫到一個新的檔案中,如果這個過程執行成功的話,就會把備份檔案删除。由此可見每次即使隻是添加一個鍵值對,也會重新寫入整個檔案的資料,這也說明SharedPreferences隻适合儲存少量資料,檔案太大會有性能問題。

接下來看下apply方法導緻ANR堆棧問題

"main" prio= tid= WAIT
  | group="main" sCount= dsCount= obj= self=
  | sysTid= nice= sched=/ cgrp=apps handle=
  | state=S schedstat=(    ) utm= stm= core=
  at java.lang.Object.wait(Native Method)
  - waiting on <> (a java.lang.VMThread) held by tid= (main)
  at java.lang.Thread.parkFor(Thread.java:)
  at sun.misc.Unsafe.park(Unsafe.java:)
  at java.util.concurrent.locks.LockSupport.park(LockSupport.java:)
  at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:)
  at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireSharedInterruptibly(AbstractQueuedSynchronizer.java:)
  at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireSharedInterruptibly(AbstractQueuedSynchronizer.java:)
  at java.util.concurrent.CountDownLatch.await(CountDownLatch.java:)
  at android.app.SharedPreferencesImpl$EditorImpl$1.run(SharedPreferencesImpl.java:)
  at android.app.QueuedWork.waitToFinish(QueuedWork.java:)
  at android.app.ActivityThread.handleServiceArgs(ActivityThread.java:)
  at android.app.ActivityThread.access$2000(ActivityThread.java:)
  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:)
  at android.os.Handler.dispatchMessage(Handler.java:)
  at android.os.Looper.loop(Looper.java:)
  at android.app.ActivityThread.main(ActivityThread.java:)
  at java.lang.reflect.Method.invokeNative(Native Method)
  at java.lang.reflect.Method.invoke(Method.java:)
  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:)
  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:)
  at dalvik.system.NativeStart.main(Native Method)
           

可以看到QueuedWork.waitToFinish方法最終會等待SharedPreference類裡的一個鎖, 這個很奇怪, 我們沒有直接在主線程裡去調用SharedPreference的commit操作,但是居然因為SharedPreference導緻ANR。

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);
}
           

可以看到apply方法會将等待寫入到檔案系統的任務放在QueuedWork的等待完成隊列裡。

是以如果我們使用SharedPreference的apply方法, 雖然該方法可以很快傳回, 并在其它線程裡将鍵值對寫入到檔案系統, 但是當Activity的onPause等方法被調用時,會等待寫入到檔案系統的任務完成,是以如果寫入比較慢,主線程就會出現ANR問題。