android强引用缓存工具-LruCache

       最近负责公司项目中的图片和文件加载缓存模块,用上了现在主流缓存框架的三级缓存:内存(软引用,强引用)、本地磁盘、网络。其中强引用的部分用了LruCache。
       LruCache是android提供的一个缓存工具,在Api 12上出现,在api12以下可以导入support v4包进行使用。android设备版本升级的速度还是太慢了啊。官方地址:https://developer.android.com/reference/android/util/LruCache.html
       LruCache使用的是最近最少使用的算法,最多缓存设定的固定内存大小的数据,当缓存快满时,最久未使用的图片或者文件会被移除,并且保证了线程的安全性。
       官方说明:A cache that holds strong references to a limited number of values. Each time a value is accessed, it is moved to the head of a queue. When a value is added to a full cache, the value at the end of that queue is evicted and may become eligible for garbage collection.

       缓存的数据会由LinkedHashMap来维护,缓存数据或者访问数据时会把元素放在或者移动到链表头部
private final LinkedHashMap<K, V> map;
void recordAccess(HashMap<K,V> m) {
    LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
    if (lm.accessOrder) {
        lm.modCount++;
        remove();
        addBefore(lm.header);
    }
}

LruCache有一个构造方法:首先需要设定cache的缓存大小
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);
}

一般初始化内存为未运行内存的1/8
int maxMemory = (int) Runtime.getRuntime().maxMemory();
	int cacheSize = maxMemory / 8;
	这里缓存的是图片bitmap,以url为key
 lruImageCache = new LruCache<String, Bitmap>(cacheSize) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                return (int) FileCacheUtils.getBitmapsize(value);
            }
        };

这里有几个比较重要的方法
protected intsizeOf(K key, V value):一般需要重写,默认返回item数量,重写计算每个item占用内存大小
By default, the cache size is measured in the number of entries. Override sizeOf(K, V) to size the cache in different units. For example, this cache is limited to 4MiB of bitmaps:
int cacheSize = 4 * 1024 * 1024; // 4MiB
   LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) {
       protected int sizeOf(String key, Bitmap value) {
           return value.getByteCount();
       }
   }

protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) {}
If your cached values hold resources that need to be explicitly released, override entryRemoved(boolean, K, V, V).
如果缓存的某个item需要释放,那么需要重写这个方法

protected V create(K key)
If a cache miss should be computed on demand for the corresponding keys, override create(K). This simplifies the calling code, allowing it to assume a value will always be returned, even when there's a cache miss.
如果需要在缓存的item未命中的情况下仍然要返回一个值请重写create

public void trimToSize(int maxSize) 
Remove the eldest entries until the total of remaining entries is at or below the requested size.
LruCache核心算法,根据内存预设值删除尾,maxSize为-1时清空全部

public final void evictAll() 
清空数据

------------------

总之,LruCache还是很赞的,是一个比较经典的缓存算法,核心原理可以看看LinkedHashMap源码和trimToSize方法。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值