LruCache的核心原理就是对LinkedHashMap的有效利用,它的内部存在一个LinkedHashMap成员变量,值得注意的4个方法:构造方法、get、put、trimToSize
LRU(Least Recently Used)缓存算法便应运而生,LRU是最近最少使用的算法,它的核心思想是当缓存满时,会优先淘汰那些最近最少使用的缓存对象。采用LRU算法的缓存有两种:LrhCache和DisLruCache,分别用于实现内存缓存和硬盘缓存,其核心思想都是LRU缓存算法。
原理
LruCache的核心思想很好理解,就是要维护一个缓存对象列表,其中对象列表的排列方式是按照访问顺序实现的,即一直没访问的对象,将放在队头,即将被淘汰。而最近访问的对象将放在队尾,最后被淘汰。(队尾添加元素,队头删除元素)
LruCache 其实使用了 LinkedHashMap 双向链表结构。
LruCache的核心原理就是对LinkedHashMap 对象的有效利用。在构造方法中设置maxSize并将accessOrder设为true,执行get后会将访问元素放到队列尾,put操作后则会调用trimToSize维护LinkedHashMap的大小不大于maxSize。
核心方法
构造方法
从LruCache的构造函数中可以看到正是用了LinkedHashMap的访问顺序。
/**
* @param maxSize for caches that do not override {@link #sizeOf}, this is
* the maximum number of entries in the cache. For all other caches,
* this is the maximum sum of the sizes of the entries in this 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);//accessOrder被设置为true
}
put()方法
可以看到put()方法重要的就是在添加过缓存对象后,调用 trimToSize()方法来保证内存不超过maxSize
/**
* Caches {@code value} for {@code key}. The value is moved to the head of
* the queue.
*
* @return the previous value mapped by {@code key}.
*/
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++;//插入缓存对象加1
size += safeSizeOf(key, value);//增加已有缓存的大小
previous = map.put(key, value);//向map中加入缓存对象
if (previous != null) {
//如果已有缓存对象,则缓存大小恢复到之前
size -= safeSizeOf(key, previous);
}
}
if (previous != null) {
//entryRemoved()是个空方法,可以自行实现
entryRemoved(false, key, previous, value);
}
trimToSize(maxSize);//调整缓存大小(关键方法)
return previous;
}
trimToSize方法
trimToSize()方法不断地删除LinkedHashMap中队头的元素,即近期最少访问的,直到缓存大小小于最大值。
/**
* Remove the eldest entries until the total of remaining entries is at or
* below the requested size.
*
* @param maxSize the maximum size of the cache before returning. May be -1
* to evict even 0-sized elements.
*/
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) {
break;
}
// 取出 map 中最老的映射
Map.Entry<K, V> toEvict = map.eldest();
if (toEvict == null) {
break;
}
key = toEvict.getKey();
value = toEvict.getValue();
map.remove(key);
size -= safeSizeOf(key, value);
evictionCount++;
}
entryRemoved(true, key, value, null);
}
}
get方法
当调用LruCache的get()方法获取集合中的缓存对象时,就代表访问了一次该元素,将会更新队列,保持整个队列是按照访问顺序排序。这个更新过程就是在LinkedHashMap中的get()方法中完成的。
/**
* Returns the value for {@code key} if it exists in the cache or can be
* created by {@code #create}. If a value was returned, it is moved to the
* head of the queue. This returns null if a value is not cached and cannot
* be created.
*/
public final V get(K key) {
if (key == null) {
//key不能为空
throw new NullPointerException("key == null");
}
V mapValue;
synchronized (this) {
mapValue = map.get(key);//获取对应的缓存对象
if (mapValue != null) {
hitCount++;
return mapValue;
}
missCount++;
}
使用示例
//1.初始化
//①设置LruCache缓存的大小,一般为当前进程可用容量的1/8。
//②重写sizeOf方法,计算出要缓存的每张图片的大小。
int maxSize=(int)Runtime.getRuntime().maxMemory()/8; //为总内存的1/8
LruCache<String,Bitmap> cache=new LruCache<String,Bitmap>(maxSize)
{
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getByteCount();
}
}
//2.放入缓存
cache.put(key:String, value:Bitmap)
//3.取出缓存
cache.get(key:String)
相关参考
http://www.xujingzi.com/nav/m/84804.html
https://www.jianshu.com/p/b49a111147ee