Android相关

android SharedPreferences源码解析

2018-01-30  本文已影响17人  LeonXtp
总体认识

image

图片来自掘金文章,我就懒得再画一次了哈。

SharedPreferences是个接口,SharedPreferenceImpl是其实现。

而Editor是SharedPreferences的内部类,也是一个接口。EditorImpl是其实现,它是SharedPreferenceImpl的内部类。

看看它们都提供了什么方法:

image.png

可以看到它支持5种基本数据类型的存取:boolean , int, float, long, String,和一个Set集合:Set<String>。

基本用法

    private void simpleSP(Context context) {
        
        SharedPreferences sp = context.getSharedPreferences("leonxtp", MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("my_key", "leonxtp");
//        editor.commit();
        editor.apply();

        String leonxtp = sp.getString("my_key", "");
        Log.i("SP", leonxtp);
    }

SharedPreferences是怎么存的?

磁盘上:

数据以xml形式存储在/data/data/项目包名/shared_prefs/sp_name.xml

image

图片来自简书文章

内存中:

SharedPreferenceImpl.java:

final class SharedPreferencesImpl implements SharedPreferences {

    @GuardedBy("ContextImpl.class")
    private ArrayMap<String, File> mSharedPrefsPaths;

    @GuardedBy("ContextImpl.class")
    private static ArrayMap<String, ArrayMap<File, SharedPreferencesImpl>> sSharedPrefsCache;

    @GuardedBy("mLock")
    private Map<String, Object> mMap;

    public final class EditorImpl implements Editor {

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

    }
}

他们的存储关系是:

OK,总体上的认知就到这吧,开始上源码

源码分析


我们通过context来获取,而ContextImpl是它的实现,这个过程是怎么完成的,可以看我之前的文章。

我们直接来到ContextImpl.java:

    @Override
    public SharedPreferences getSharedPreferences(String name, int mode) {
        
        // At least one application in the world actually passes in a null
        // name.  This happened to work because when we generated the file name
        // we would stringify it to "null.xml".  Nice.
        // 这里谷歌开发人员写了一段感觉很自娱自乐的注释,我们可以看到,它允许null值哦
        if (mPackageInfo.getApplicationInfo().targetSdkVersion <
                Build.VERSION_CODES.KITKAT) {
            if (name == null) {
                name = "null";
            }
        }

        File file;
        synchronized (ContextImpl.class) {
            if (mSharedPrefsPaths == null) {
                mSharedPrefsPaths = new ArrayMap<>();
            }
            file = mSharedPrefsPaths.get(name);
            if (file == null) {
                file = getSharedPreferencesPath(name);
                mSharedPrefsPaths.put(name, file);
            }
        }
        return getSharedPreferences(file, mode);
    }

先看内存中有没有这个xml文件的对象,没有就创建,加入到 mSharedPrefsPaths中。创建的代码如下:

    @Override
    public File getSharedPreferencesPath(String name) {
        return makeFilename(getPreferencesDir(), name + ".xml");
    }

    private File makeFilename(File base, String name) {
        if (name.indexOf(File.separatorChar) < 0) {
            return new File(base, name);
        }
        throw new IllegalArgumentException(
                "File " + name + " contains a path separator");
    }

很简单,其中getPreferencesDir()获取到目录就是/data/data/我们的程序包名/shared_prefs/。

有了文件之后,就尝试去取出SharedPreferenceImpl对象了:

    @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);
                // ...

                // 创建的时候,会将xml文件加载到mMap中
                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.
            // 这里主要针对mode为多进程的时候
            sp.startReloadIfChangedUnexpectedly();
        }
        return sp;
    }

创建SharedPreferenceImpl的时候会将xml文件加载到mMap中,过程如下:

final class SharedPreferencesImpl implements SharedPreferences {

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

}

这里看到,它使用了同步代码块保证多线程的同步。
而mMap就是从xml文件中解析出来的。进去看看,还是不看了吧,就是用了XmlParser解析而已。

OK,获取(创建)的过程看完了,下面看看put操作,

    public final class EditorImpl implements Editor {

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

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

就这么简单??是的,毕竟,真正的操作在commit/apply里:

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

注意这两行:

            SharedPreferencesImpl.this.enqueueDiskWrite(
                mcr, null /* sync write on this thread okay */);
            try {
                mcr.writtenToDiskLatch.await();
            } catch (InterruptedException e) {
                return false;
            }

writtenToDiskLatch是一个CountDownLatch对象,它将会等待enqueueDiskWrite()方法执行完成,这就会致使线程阻塞。所以commit操作写入文件是同步的,其中commitToMemory是将mModified中的修改写入到内存中。

        // Returns true if any changes were made
        private MemoryCommitResult commitToMemory() {

            synchronized (SharedPreferencesImpl.this.mLock) {
                
                mapToWriteToDisk = mMap;

                boolean hasListeners = mListeners.size() > 0;

                synchronized (mLock) {

                    for (Map.Entry<String, Object> e : mModified.entrySet()) {
                        String k = e.getKey();
                        Object v = e.getValue();

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

                    mModified.clear();

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

而写入文件操作在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 == 1;
            }
            if (wasEmpty) {
                writeToDiskRunnable.run();
                return;
            }
        }

        QueuedWork.queue(writeToDiskRunnable, !isFromSyncCommit);
    }

可以看到,它开了一个线程专门去写入文件,所以有些人说commit操作是在主线程执行的,其实并不是,它只是让主线程等待子线程完成写入而已。

那么apply()方法:

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

                    }
                };

            QueuedWork.addFinisher(awaitCommit);

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

            SharedPreferencesImpl.this.enqueueDiskWrite(mcr, postWriteRunnable);

            notifyListeners(mcr);
        }

它跟commit不同的地方就是,不在当前线程等待文件写入线程执行完毕,而是开了一个线程,并且没有返回值。所以它对于不需要返回值的调用者来说,效率更高。

再看看读取操作:

    @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) {
            }
        }
    }

读取也是同步的,先加个锁,在里面用while不断判断是否加载完成,没有就释放锁,到它继续执行的时候,又会再判断是否完成。

如此,SharedPreferences就解析完了。

小结


关于线程同步,可以参考:

java并发之原子性、可见性、有序性
volatile你了解多少?
深入浅出Synchronized
synchronized(this)、synchronized(class)与synchronized(Object)的区别

上一篇 下一篇

猜你喜欢

热点阅读