Android LruCache类分析

一. LruCache使用背景

在我们的项目开发中,多多少少都会用到图片资源,有的使用我们的图片资源还会以列表的形式展开,可想而知,当我们滑动列表的时候,如果我们一直生成数据,可想而知,肯定会发生OOM,LruCache就是为了应对这种场景产生的。

二.LruCache原理

LruCache是基于java中的LinkedHashMap实现的,我们在外部先设置这个LinkedHashMap中的所有数据元所占内存空间总和的最大值,当我们从这个容器中获取数据元素的时候,现将数据获取出来,再将其位置移动到队列的头部,这样我们能够保证最经使用的数据元素都在队列的头部,当我们向队列中添加数据的时候,计算整个队列中的所有数据元素的大小,如果数据的总大小超过分配的内存,就从队列的末尾开始销毁数据,直到数据的总大小小于或者等于分配的内存的大小。

三.源码分析

首先看LruCache的构造函数,这里我们传入这个缓存池的最大的大小,同时设置LinkedHashMap为访问模式,也就是当我们从LinkedHashMap中get一个数据的时候,将该数据移到队列的头部。

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);
    }
再看一下LruCache中的存放数据的函数,

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 += safeSizeOf(key, value);
            previous = map.put(key, value);
            if (previous != null) {
                size -= safeSizeOf(key, previous);
            }
            
            Log.info(TAG, "LruCache put____________________size:" + size);
        }

        if (previous != null) {
            entryRemoved(false, key, previous, value);
        }

        trimToSize(maxSize);
        return previous;
    }

这个方法的主要意思就是,我们将简直对存放到LinkedHashMap中,在添加后,我们在计算整个容器的大小,判断其是否超过之前设置的最大空间值,如果超过就从队列的最后面开始销毁数据,具体方法 trimToSize(maxSize);如下:

    private 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!");
                	break;
                }

                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++;
                
                Log.info(TAG, "LruCache trimToSize____________________size:" + size);
            }

            entryRemoved(true, key, value, null);
        }
    }

最后再看一下从缓存池中获取数据的放法:

 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.
         */

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

        synchronized (this) {
            createCount++;
            mapValue = map.put(key, createdValue);

            if (mapValue != null) {
                // There was a conflict so undo that last put
                map.put(key, mapValue);
            } else {
                size += safeSizeOf(key, createdValue);
                Log.info(TAG, "LruCache get____________________size:" + size);
            }
        }

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

        我们先从缓存池中获取数据,如果获取的数据为null,这个时候我们尝试去创建一个Null值的数据返回,但是到我们执行Create方法的时候,整个缓存池可能会发生变化,所以后面又做了一些处理,整个逻辑还是比较严谨的。


好,对LruCache分析就到这,如果有理解不对,还请指出,下一篇讲解LruCache的具体使用,谢谢!


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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值