LruCache使用以及源码分析

LruCache使用以及源码分析

引言 :  Android开发中我们或多或少都需要用到的图片框架,不同的框架内部都有自己不同的缓存策略,Android原生谷歌提供了一个缓存类LruCache<K, V>,今天说一下具体的用法,然后顺便看一下内部源码的实现,也算是一种学习

在看源码之前首先大致了解一下Linkedhashmap这个类,具体学习以及源码分析放在后续的文章中,Linkedhashmap维护了一个双向链表,LinkedHashMap保证了元素迭代的顺序,但是会牺牲掉一定的性能

使用方法

首先介绍具体的使用,使用没有什么特别复杂的设置,只需要根据实际情况重写sizeOf(),entryRemoved(),create().

        //举个栗子^_^
        final int MAX_SIZE = 1024 * 1024 * 10;//10 M
        LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>
        (MAX_SIZE) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                //计算添加数据的大小
                return value.getByteCount();
            }

            @Override
            protected void entryRemoved(boolean evicted, String key,
            Bitmap oldValue, Bitmap newValue) {
                //处理被删除的数据
                super.entryRemoved(evicted, key, oldValue, newValue);
            }

            @Override
            protected Bitmap create(String key) {
                //用于get的时候如果获取不到值,自己根据自己的方法创建value
                return super.create(key);
            }
        };
       synchronized (cache) {
           if (cache.get(key) == null) {
               cache.put(key, value);
       }}

构造方法

看一下构造方法,构造方法比较简单,首先是对缓存值的大小进行赋值,然后创建一个LinkedHashMap,后续的所有操作都是围绕这个类展开的

    public LruCache(int maxSize) {
        if (maxSize <= 0) {
            throw new IllegalArgumentException("maxSize <= 0");
        }
        this.maxSize = maxSize;
        this.map = new LinkedHashMap<K, V>(0, 0.75f, true);
    }

trimToSize( )

重要的方法,该方法是起到口控制缓存容量大小的关键方法, 核心方法,具体来看下面的源码

    //maxSize表示用户设定的缓存容量大小
    public void trimToSize(int maxSize) {
        //注意这是一个死循环,只有当集合中的总容量小于最大值的时候才会跳出循环
        while (true) {
            K key;
            V value;
            //同步控制
            synchronized (this) {
                //非空判断,合法值校验
                if (size < 0 || (map.isEmpty() && size != 0)) {
                    throw new IllegalStateException(getClass().getName()
                            + ".sizeOf() is reporting inconsistent results!");
                }
                //如果小与规定大小,就不需要处理了
                if (size <= maxSize) {
                    break;
                }
                //返回head
                Map.Entry<K, V> toEvict = map.eldest();
                if (toEvict == null) {
                    break;
                }

                key = toEvict.getKey();
                value = toEvict.getValue();
                map.remove(key);
                //计算要移除值得的大小,修改size
                size -= safeSizeOf(key, value);
                evictionCount++;
            }
            //将移除的值返回
            entryRemoved(true, key, value, null);
        }
    }

put( )

    public final V put(K key, V value) {
        //对key,value进行校验
        if (key == null || value == null) {
            throw new NullPointerException("key == null || value == null");
        }

        V previous;
        synchronized (this) {
            putCount++;
            //对计算要加入的value的大小,这个值就最终调用的是我们重写的 sizeOf()方法
            size += safeSizeOf(key, value);
            //将键值对加入集合中,同时判断是否有数据返回,如果有数据(该数据为原先的key中返回的value)返回就
            //计算大小,并且修改size的值
            previous = map.put(key, value);
            if (previous != null) {
                size -= safeSizeOf(key, previous);
            }
        }
        //返回原先要被移除的值,可以自重写的entryRemoved()方法中获取该值,进行相关操作
        if (previous != null) {
            entryRemoved(false, key, previous, value);
        }
        //修改size大小,是集合中所有的size值低于设定的最大值
        trimToSize(maxSize);
        return previous;
    private int safeSizeOf(K key, V value) {
        int result = sizeOf(key, value);
        if (result < 0) {
            throw new IllegalStateException("Negative size: " + key + "=" + value);
        }
        return result;
    }

get( )

基本思路跟put()一样,注意源码中英文注释

    public final V get(K key) {
        //非空校验
        if (key == null) {
            throw new NullPointerException("key == null");
        }
        //如果该key有value,那么直接返回value
        V mapValue;
        synchronized (this) {
            mapValue = map.get(key);
            if (mapValue != null) {
                hitCount++;
                return mapValue;
            }
            missCount++;
        }
        //如果没有该值,那么走创建方法
        /*
         * Attempt to create a value. This may take a long time, and the map
         * may be different when create() returns. If a conflicting value was
         * added to the map while create() was working, we leave that value in
         * the map and release the created value.
         */
        //根据该key用户选择是否创建value
        V createdValue = create(key);
        if (createdValue == null) {
            return null;
        }

        synchronized (this) {
            createCount++;
            mapValue = map.put(key, createdValue);
            //按官方介绍,create()创建是有延迟的,说白了就是异步的,假设两次都输入同一个key,因为创建是异步
            //的,所以存在冲突,例如调用了两次get()方法,但是第一次的创建延迟了,第二次的创建抢占资源,那么实际应该             
            //获取的数据是刚开始创建的
            if (mapValue != null) {
                // There was a conflict so undo that last put
                map.put(key, mapValue);
            } else {
                size += safeSizeOf(key, createdValue);
            }
        }
        //修改size
        if (mapValue != null) {
            entryRemoved(false, key, createdValue, mapValue);
            return mapValue;
        } else {
            trimToSize(maxSize);
            return createdValue;
        }
    }

remove( )

    public final V remove(K key) {
        if (key == null) {
            throw new NullPointerException("key == null");
        }
        //修改size大小
        V previous;
        synchronized (this) {
            previous = map.remove(key);
            if (previous != null) {
                size -= safeSizeOf(key, previous);
            }
        }
        //删除数据
        if (previous != null) {
            entryRemoved(false, key, previous, null);
        }

        return previous;
    }

remove( )

    public void resize(int maxSize) {
        if (maxSize <= 0) {
            throw new IllegalArgumentException("maxSize <= 0");
        }

        synchronized (this) {
            this.maxSize = maxSize;
        }
        trimToSize(maxSize);
    }

总结

开心的总结时刻,LruCache算发主要是用作内存缓存,当然了实际情况还是需要结合磁盘缓存来使用的,要理解该算法只需要记住两点就可以了,一个是LinkedHashMap的使用以及特性,另一个是trimToSize( ) 方法,只要记住这两方面,理解起来就没有什么问题了,当然了最后还是希望如果发现什么错误欢迎私信或留言指正

邮    箱: [email protected]

github: https://github.com/ASCN-BJ

猜你喜欢

转载自blog.csdn.net/Buuuuuuuuu/article/details/80008846
今日推荐