LruCache是Android 内置的一种缓存类,可以直接使用,方便的帮助我们实现缓存,他是基于LRU算法的,如果你的课本知识还没还给老师,你应该还记得在学习内存页面置换算法时,有一种算法就是LRU,我么你先来简单介绍一下。
LRU就是Least Recently Used的简写,字面意思就是最近最久未使用。在缺页发生时,选择最久未使用的页面淘汰,他是根据局部性原理产生的一种算法,局部性原理任务最近一段时间使用过的页面在未来可能也会再次使用,所以淘汰最久未使用的页面,我们通过一个图理解一下比较直观:
1 2 3 4 5 6 7 8 9 10
Req c a d b e b a b c d
------------------------------------
1 c c c c e e e e e d
2 a a a a a a a a a
3 d d d d d d c c
4 b b b b b b b
如上面所示,在第5次请求时,发生缺页,但是已存满,需要淘汰一个,最近使用的3个页面是a d b,所以淘汰c页面,使e页面进入内存,后面的也都差不多,这里只是简单介绍一下,详细的细节可以上网找资料。
下面就来具体看一下源码,先从构造函数开始:
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);
}
首先要在构造中指定这个缓存的总大小,这是必须的。接下来初始化了一个map,这个map比较特殊,是LinkedHashMap类型的,这个类型的可能用的比较少,简单介绍一下。
LinkedHashMap也是一种Map,他是继承于HashMap的,LinkedHashMap是基于链表的,而且是双向链表,使用双向链表的原因是为了弥补HashMap无序存储的缺点,LinkedHashMap虽然增加了时间和空间的开销,但是能保证访问有序,这也给我们实现LRU算法提供了便利。上面LruCache初始化时,LinkedHashMap构造的第二个参数设为true,就是访问有序,这也就是LRU实现的基础。
接下来看LruCache的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 += safeSizeOf(key, value);
previous = map.put(key, value);
if (previous != null) {
size -= safeSizeOf(key, previous);
}
}
if (previous != null) {
entryRemoved(false, key, previous, value);
}
trimToSize(maxSize);
return previous;
}
最开始判断数据的有效性没有什么问题,接下来的自增自减可能有些朋友会有疑问。这里的逻辑是这样的:首先假设该key没有存过,所以将size自增(safeSizeOf就是调用的sizeOf,sizeOf就是我们重写的,计算每个对象大小的方法),然后put该对象。
如果你对put方法很熟悉下面的逻辑应该很好理解,put方法其实是有返回值的,如果该key没有存储过,就将对象存进去,返回null,如果该key已经存在,就把之前的value用新的代替,返回旧的value。这里如果previous != null,就代表有value更新,当然需要把旧的value大小减去。
接下来如果有内容被替换,回调entryRemoved方法,这个需要我们自己实现。
下面调用了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) {
break;
}
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);
}
}
这里就体现到了有限缓存的概念,首先,判断是否溢出,若是则移除最早的对象(map.eldest()),一直循环直到容量小于预定值为止。
下面看个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++;
}
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);
}
}
if (mapValue != null) {
entryRemoved(false, key, createdValue, mapValue);
return mapValue;
} else {
trimToSize(maxSize);
return createdValue;
}
}
逻辑很清晰而且简单,首先就是get给定的key,若拿到值就返回,没有的话调用create方法创建一个,这个方法默认返回为null,需要我们自己实现,也就是缓存中没有的情况下,需要取得方法。若create成功的话,自动加入缓存。