LruCache实现原理
关于Android的三级缓存,其中主要的就是内存缓存和硬盘缓存。
这两种缓存机制的实现都应用到了LruCache算法,今天我们就从使用到源码解析,来彻底理解Android中的缓存机制。
一、Android中的缓存策略
一般来说,缓存策略主要包含缓存的添加、获取和删除这三类操作。如何添加和获取缓存这个比较好理解,那么为什么还要删除缓存呢?这是因为不管是内存缓存还是硬盘缓存,它们的缓存大小都是有限的。当缓存满了之后,再想其添加缓存,这个时候就需要删除一些旧的缓存并添加新的缓存。
因此LRU(Least Recently Used)缓存算法便应运而生,LRU是近期最少使用的算法,它的核心思想是当缓存满时,会优先淘汰那些近期最少使用的缓存对象。采用LRU算法的缓存有两种:LrhCache和DisLruCache,分别用于实现内存缓存和硬盘缓存,其核心思想都是LRU缓存算法。
1.LruCache的介绍
LruCache是个泛型类,主要算法原理是把最近使用的对象用强引用(即我们平常使用的对象引用方式)存储在 LinkedHashMap 中。当缓存满时,把最近最少使用的对象从内存中移除,并提供了get和put方法来完成缓存的获取和添加操作。
先看下LruCache的 源码
public class LruCache { private final LinkedHashMap map; //存放数据的集合 private int size; //当前LruCahce的内存占用大小 private int maxSize; //Lrucache的最大容量 private int putCount; //put的次数 private int createCount; //create的次数 private int evictionCount; //回收的次数 private int hitCount; //命中的次数 private int missCount; //丢失的次数
构造方法:
public LruCache(int maxSize) { if (maxSize <= 0) { throw new IllegalArgumentException("maxSize <= 0"); } this.maxSize = maxSize; this.map = new LinkedHashMap(0, 0.75f, true); }
LinkedHashMap的构造方法:
public LinkedHashMap(int initialCapacity, float loadFactor, boolean accessOrder) { super(initialCapacity, loadFactor); this.accessOrder = accessOrder; }
其中accessOrder设置为true则为访问顺序,为false,则为插入顺序。
以具体例子解释:
当设置为true时:
public static final void main(String[] args) { LinkedHashMap map = new LinkedHashMap<>(0, 0.75f, true); map.put(0, 0); map.put(1, 1); map.put(2, 2); map.put(3, 3); map.put(4, 4); map.put(5, 5); map.put(6, 6); map.get(1); map.get(2); for (Map.Entry entry : map.entrySet()) { System.out.println(entry.getKey() + ":" + entry.getValue()); } }
输出结果:
0:03:34:45:56:61:12:2
当设置为false的时候,输出顺序为:
0:01:12:23:34:45:56:6
有以上结果可以看出,这个设置为true的时候,如果对一个元素进行了操作(put、get),就会把那个元素放到集合的最后,设置为false的时候,无论怎么操作,集合元素的顺序都是按照插入的顺序来进行存储的。
到了这里我们可以知道,这个LinkedHashmap正是实现Lru算法的核心之处,当内容容量达到最大值的时候,只需要移除这个集合的前面的元素直到集合的容量足够存储数据的时候就可以了。
下面我们来看一看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) { //插入的缓存对象值加1 putCount++; //增加已有缓存的大小 size += safeSizeOf(key, value); //向map中加入缓存对象 previous = map.put(key, value); //如果已有缓存对象,则缓存大小恢复到之前 if (previous != null) { size -= safeSizeOf(key, previous); } } //entryRemoved()是个空方法,可以自行实现 if (previous != null) { entryRemoved(false, key, previous, value); } //调整缓存大小(关键方法) trimToSize(maxSize); return previous; }
可以看到put()方法并没有什么难点,重要的就是在添加过缓存对象后,调用 trimToSize()方法,来判断缓存是否已满,如果满了就要删除近期最少使用的算法。
trimToSize()方法
public void trimToSize(int maxSize) { //死循环 while (true) { K key; V value; synchronized (this) { //如果map为空并且缓存size不等于0或者缓存size小于0,抛出异常 if (size < 0 || (map.isEmpty() && size != 0)) { throw new IllegalStateException(getClass().getName() + ".sizeOf() is reporting inconsistent results!"); } //如果缓存大小size小于最大缓存,或者map为空,不需要再删除缓存对象,跳出循环 if (size <= maxSize || map.isEmpty()) { break; } //迭代器获取第一个对象,即队尾的元素,近期最少访问的元素 Map.Entry toEvict = map.entrySet().iterator().next(); key = toEvict.getKey(); value = toEvict.getValue(); //删除该对象,并更新缓存大小 map.remove(key); size -= safeSizeOf(key, value); evictionCount++; } entryRemoved(true, key, value, null); } }
这个方法是一个无限循环,跳出循环的条件是,size < maxSize或者 map 为空。主要的功能是判断当前容量时候已经超出最大的容量,如果超出了maxSize的话,就会循环移除map中的第一个元素,即删除LinkedHashMap中队尾的元素,即近期最少访问的,直到达到跳出循环的条件。由上面的分析知道,map中的第一个元素就是最近最少使用的那个元素。
研究完了put方法之后,下面开始研究get方法。
public final V get(K key) { if (key == null) { throw new NullPointerException("key == null"); } V mapValue; synchronized (this) { //获取对应的缓存对象 //get()方法会实现将访问的元素更新到队列头部的功能 mapValue = map.get(key); if (mapValue != null) { hitCount++; //命中 + 1 return mapValue; } missCount++;//丢失+1 } V createdValue = create(key); //创建 if (createdValue == null) { return null; } synchronized (this) { createCount++; //创建 + 1 mapValue = map.put(key, createdValue); if (mapValue != null) { // There was a conflict so undo that last put //如果有矛盾,意思就是有旧的值,就撤销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; } }
当调用LruCache的get()方法获取集合中的缓存对象时,就代表访问了一次该元素,将会更新队列,保持整个队列是按照访问顺序排序。这个更新过程就是在LinkedHashMap中的get()方法中完成的。
最后说一下remove方法:
public final V remove(K key) { if (key == null) { throw new NullPointerException("key == null"); } 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; }
由此可见LruCache中维护了一个集合LinkedHashMap,该LinkedHashMap是以访问顺序排序的。当调用put()方法时,就会在结合中添加元素,并调用trimToSize()判断缓存是否已满,如果满了就用LinkedHashMap的迭代器删除队尾元素,即近期最少访问的元素。当调用get()方法访问缓存对象时,就会调用LinkedHashMap的get()方法获得对应集合元素,同时会更新该元素到队头。
LruCache的使用:
int maxMemory = (int) (Runtime.getRuntime().totalMemory()/1024); int cacheSize = maxMemory/8; mMemoryCache = new LruCache(cacheSize){ @Override protected int sizeOf(String key, Bitmap value) { return value.getRowBytes()*value.getHeight()/1024; } };
①设置LruCache缓存的大小,一般为当前进程可用容量的1/8。
②重写sizeOf方法,计算出要缓存的每张图片的大小。
注意:缓存的总容量和每个缓存对象的大小所用单位要一致。
更多相关文章
- 简单的Android ROM制作方法:创建刷机包 备份ROM
- 彻底解析Android缓存机制——LruCache
- Android原生Switch控件滑块thumb卡住问题的解决方法
- Android 静默安装和智能安装的实现方法
- 将android Market缓存转移到SD卡的小程序
- Android 缓存策略
- Android中Handler的使用方法——在子线程中更新界面
- Android网络编程之通过Get方法实现
- android控件的监听绑定方法