android.util.LruCache主要代码分析

LruCache在android.util包下,顾名思义,可以翻译为最近最少使用缓存,它用强引用保存需要缓存的对象,它内部维护一个队列(实际上是LinkedHashMap内部的双向链表),当其中的一个值被访问时,它被放到队列的尾部,当缓存将满时,队列头部的值(也就是最近最少被访问的)被丢弃,之后可以被垃圾回收。

LruCache比较重要的几个方法是:

public final V get (K key):返回cache中key对应的值,调用这个方法后,被访问的值会移动到队列的尾部

public final V put (K key, V value):根据key存放value,存放的value会移动到队列的尾部

protected int sizeOf (K key, V value) :返回每个缓存对象的大小,这个用来判断缓存是否快要满了的情况,这个方法必须重写

protected void entryRemoved (boolean evicted, K key, V oldValue, V newValue):当一个缓存对象被丢弃时候调用的方法,这个是个空方法,可以重写,不是必需的,第一个参数为true:当缓存对象是为了腾出空间而被清理时(trimToSize时)。第一个参数为false:缓存对象的entry被remove移除或者被put覆盖时。

public void trimToSize (int maxSize):检测当前缓存队列是否已满,如果满了,移除队列头部的缓存对象


下面分析下它的源码。

比较重要的成员变量:

    private int size;
    private int maxSize;

size是当前所有缓存的对象的总大小。

maxSize是构造方法传入的参数,指定了总缓存的大小上限。


构造方法:

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

可以看到,其实它的内部维护了一个LinkedHashMap,LinkedHashMap构造第三个参数为true,表明它内部的双向链表是根据元素被访问顺序来排序的。

put方法:

    public final V put(K key, V value) {
        if (key == null || value == null) {
            throw new NullPointerException("key == null || value == null");
        }
        V previous;
        synchronized (this) {
            putCount++;
            //维护size变量
            size += safeSizeOf(key, value);
           //看这个key之前有没有被使用过,如果用过返回值不为null
            previous = map.put(key, value);
           //如果之前的缓存被现在的覆盖了,减去它原来的大小
            if (previous != null) {
                size -= safeSizeOf(key, previous);
            }
        }
        //如果之前的entry被覆盖了,第一个对被覆盖的值和新值的处理交给子类覆写
        if (previous != null) {
            entryRemoved(false, key, previous, value);
        }
        //整理空间
        trimToSize(maxSize);
        return previous;
    }
put中用到的方法:safeSizeOf

    private int safeSizeOf(K key, V value) {
        int result = sizeOf(key, value);
        if (result < 0) {
            throw new IllegalStateException("Negative size: " + key + "=" + value);
        }
        return result;
    }
可以看到其实就是调用了sizeOf方法,而sizeOf是需要重写的,用来计算每个缓存对象的大小。

put中用到的方法:trimToSize:

    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 || map.isEmpty()) {
                    break;
                }
                //移除的操作
                Map.Entry<K, V> toEvict = map.entrySet().iterator().next();
                key = toEvict.getKey();
                value = toEvict.getValue();
                map.remove(key);
                size -= safeSizeOf(key, value);
                evictionCount++;
            }

            entryRemoved(true, key, value, null);
        }
    }
作用是,在当前缓存大小超过或等于最大上限时,移除map中链表头部的缓存对象(对于按照元素被访问顺序来排序的LinkedHashMap,最近访问的元素被放在内部链表的尾部,最早访问的元素在链表头部)。

get方法:

    public final V get(K key) {
        if (key == null) {
            throw new NullPointerException("key == null");
        }

        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.
         * 如果需要获取的缓存不存在,即 mapValue = map.get(key);为null,则调用create方法,
         * create方法需要覆写,但不是必需的。create方法存在一个执行过程,如果在这个执行过程中,
         * map发生了变化(create方法不是线程安全的,一个冲突的值被put,比如原来get("abc")==null,
         * 但是执行create的时候发生了put("abc","xxx")的操作,  则这个create的值会被移除)
         */

        V createdValue = create(key);
        if (createdValue == null) {
            return null;
        }

        synchronized (this) {
            createCount++;
            mapValue = map.put(key, createdValue);
            //产生了冲突,create的时候在相同的key上发生了put操作
            if (mapValue != null) {
                // 还原上次put的值
                map.put(key, mapValue);
            } else {
                size += safeSizeOf(key, createdValue);
            }
        }

        if (mapValue != null) {
            entryRemoved(false, key, createdValue, mapValue);
            return mapValue;
        } else {
            trimToSize(maxSize);
            return createdValue;
        }
    }
sizeof:

    protected int sizeOf(K key, V value) {
        return 1;
    }

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值