android SharedPreferences源码解析

总体认识

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

    }
}

他们的存储关系是:

  • 从文件的角度来说,

    一个包名对应一个存储目录,里面有多个xml文件,一个xml文件对应一个map,里面多个key-value

  • 从内存的角度来说,

    sSharedPrefsCache中保存的是app中所有的xml文件对应的操作它的SharedPreferencesImpl的对象,据查源码,它内部只保存了一个键值对,key就是app的包名。

    mSharedPrefsPaths保存的是文件名-文件列表,

    mMap保存的是某个xml文件对应的内容。

    mModified中保存的是修改过的内容,它会在commit和apply之后,保存到mMap中,并且同步/异步写进xml文件里。

    Android这样设计的目的就是避免每次读写都去操作文件,带来很大的性能消耗。

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就解析完了。

小结

  • 它采用通过XmlParser将文件以Map的形式加载到内存中的方式,避免频繁文件读写。
  • 它将修改保存在一个临时的Map中,commit/apply的时候,再统一提交到内存和文件中。
  • commit操作会阻塞当前线程,不需要等待SharedPreferences操作结果的话,使用apply()效率更高
  • 第一次使用SharedPreferences时,它有一个异步读取xml文件到内存的过程,所以立即读取值的话会失败。

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

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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 219,701评论 6 508
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 93,649评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,037评论 0 356
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,994评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,018评论 6 395
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,796评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,481评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,370评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,868评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,014评论 3 338
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,153评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,832评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,494评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,039评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,156评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,437评论 3 373
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,131评论 2 356

推荐阅读更多精彩内容