1、LruCache是一个泛型类,它内部采用一个LinkedHashMap以强引用的方式存储外界的缓存对象,其提供了get和put方法来完成缓存的获取和添加操作,当缓存满时,LruCache会移除较早使用的缓存对象,然后再添加新的缓存对象。
2、为了实现LRU(最近最少使用),LruCache里面使用了LinkedHashMap。LinkedHashMap的特性:HashMap与双向链表的组合,HashMap是无序的,而加入双向链表后保证了元素的顺序
3、初始化LruCache
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);
}
// 初始化
// 当前进程的可用内存
int maxMemory = (int) (Runtime.getRuntime().maxMemory()/1024);
// 缓存大小
int cacheSize = maxMemory / 8;
LruCache memory = new LruCache<String, Bitmap>(cacheSize){
@Override
protected int sizeOf(String key, Bitmap value) {
// 返回每张图片的占用内存大小
return value.getRowBytes() * value.getHeight() / 1024;
}
@Override
protected void entryRemoved(boolean evicted, String key, Bitmap oldValue, Bitmap newValue) {
// 移除旧缓存时,调用该方法完成一些资源回收工作
super.entryRemoved(evicted, key, oldValue, newValue);
}
};
4、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相同将返回旧的value,否则返回null
previous = map.put(key, value);
if (previous != null) {
// 如果原先缓存中就有key,那么size不增加
size -= safeSizeOf(key, previous);
}
}
if (previous != null) {
// 进行资源回收工作
entryRemoved(false, key, previous, value);
}
// 判断缓存是否满,如果满了,就进行删除
trimToSize(maxSize);
return previous;
}