1、原理
缓存保存了一个强引用(Android 2.3开始,垃圾回收器更倾向于回收弱引用和软引用,软引用和弱引用变得不可靠,Android 3.0中,图片的数据会存储在本地的内存当中,因而无法用一种可预见的方式将其释放)限制值的数量. 每当值被访问的时候,它会被移动到队列的头部. 当缓存已满的时候加入新的值时,队列中最后的值会出队,可能被回收
LRUCache内部维护主要是通过LinkedHashMap实现
这是一个安全的线程,多线程缓存通过同步实现
2、使用
默认情况下,缓存的大小是由值的数量决定,重写sizeOf计算不同的值
如果你缓存值需要明确释放,重写entryRemoved()
int maxMemory = (int) Runtime.getRuntime().maxMemory();
int mCacheSize = maxMemory / 8;
//给LruCache分配1/8 4M
mMemoryCache = new LruCache<String, Bitmap>(mCacheSize){
//必须重写此方法,来测量Bitmap的大小
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight();
}
};
mMemoryCache.put(key, bitmap)
mMemoryCache.get(key)
这个类不允许有空的键值. get,put,remove 返回空值,key对应的值不在缓存中
3、源码分析
构造函数
/**
* @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);
}
初始化了最大容量和LinkedHashMap
public LinkedHashMap(
int initialCapacity, float loadFactor, boolean accessOrder) {
super(initialCapacity, loadFactor);
init();
this.accessOrder = accessOrder;
}
initialCapacity:初始化hashMap的容量,这个值必须大于等于0
loadFactor:已被忽略,取值为3/4
accessOrder:如果accessOrder为true,排序是根据最近最少使用算法,如果accessOrder为false,排序是基于插入顺序
@Override void i