LruCache在android.util包下,顾名思义,可以翻译为最近最少使用缓存,它用强引用保存需要缓存的对象,它内部维护一个队列(实际上是LinkedHashMap内部的双向链表),当其中的一个值被访问时,它被放到队列的尾部,当缓存将满时,队列头部的值(也就是最近最少被访问的)被丢弃,之后可以被垃圾回收。
LruCache比较重要的几个方法是:
public final V get (K key):返回cache中key对应的值,调用这个方法后,被访问的值会移动到队列的尾部
public final V put (K key, V value):根据key存放value,存放的value会移动到队列的尾部
protected int sizeOf (K key, V value) :返回每个缓存对象的大小,这个用来判断缓存是否快要满了的情况,这个方法必须重写
protected void entryRemoved (boolean evicted, K key, V oldValue, V newValue):当一个缓存对象被丢弃时候调用的方法,这个是个空方法,可以重写,不是必需的,第一个参数为true:当缓存对象是为了腾出空间而被清理时(trimToSize时)。第一个参数为false:缓存对象的entry被remove移除或者被put覆盖时。
public void trimToSize (int maxSize):检测当前缓存队列是否已满,如果满了,移除队列头部的缓存对象
比较重要的成员变量:
private int size;
private int maxSize;
size是当前所有缓存的对象的总大小。
maxSize是构造方法传入的参数,指定了总缓存的大小上限。
构造方法:
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);
}
可以看到,其实它的内部维护了一个LinkedHashMap,LinkedHashMap构造第三个参数为true,表明它内部的双向链表是根据元素被访问顺序来排序的。
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变量
size += safeSizeOf(key, value);
//看这个key之前有没有被使用过,如果用过返回值不为null
previous = map.put(key, value);
//如果之前的缓存被现在的覆盖了,减去它原来的大小
if (previous != null) {
size -= safeSizeOf(key, previous);
}
}
//如果之前的entry被覆盖了,第一个对被覆盖的值和新值的处理交给子类覆写
if (previous != null) {
entryRemoved(false, key, previous, value);
}
//整理空间
trimToSize(maxSize);
return previous;
}
put中用到的方法:safeSizeOf
private int safeSizeOf(K key, V value) {
int result = sizeOf(key, value);
if (result < 0) {
throw new IllegalStateException("Negative size: " + key + "=" + value);
}
return result;
}
可以看到其实就是调用了sizeOf方法,而sizeOf是需要重写的,用来计算每个缓存对象的大小。
put中用到的方法: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 || 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++;
}
entryRemoved(true, key, value, null);
}
}
作用是,在当前缓存大小超过或等于最大上限时,移除map中链表头部的缓存对象(对于按照元素被访问顺序来排序的LinkedHashMap,最近访问的元素被放在内部链表的尾部,最早访问的元素在链表头部)。
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++;
}
/*
* 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.
* 如果需要获取的缓存不存在,即 mapValue = map.get(key);为null,则调用create方法,
* create方法需要覆写,但不是必需的。create方法存在一个执行过程,如果在这个执行过程中,
* map发生了变化(create方法不是线程安全的,一个冲突的值被put,比如原来get("abc")==null,
* 但是执行create的时候发生了put("abc","xxx")的操作, 则这个create的值会被移除)
*/
V createdValue = create(key);
if (createdValue == null) {
return null;
}
synchronized (this) {
createCount++;
mapValue = map.put(key, createdValue);
//产生了冲突,create的时候在相同的key上发生了put操作
if (mapValue != null) {
// 还原上次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;
}
}
sizeof:
protected int sizeOf(K key, V value) {
return 1;
}