Least Recently Used => LRU:最近最少使用算法
為什么使用LRUcache?
Android2.3開始,GC更傾向于回收弱引用和軟引用,變得不可靠。
Android3.0中,圖片的數據會存儲在本地的內存當中,限制值的數量. 每當值被訪問的時候,它會被移動到隊列的頭部. 當緩存空間已滿加入在新的值時,隊列中最后的值會出隊,可能被回收。
原理:
LruCache 使用一個 LinkedHashMap 簡單的實現內存的緩存,沒有軟引用,都是強引用。如果添加的數據大于設置的最大值,就刪除(最近最少使用)最先緩存的數據來調整內存。
maxSize 是通過構造方法初始化的值,最大緩存值。
size 在添加和移除緩存都被更新值,他通過 safeSizeOf 這個方法更新值。safeSizeOf方法內部調用的sizeOf方法默認返回 1,但一般我們會根據 maxSize 重寫這個方法,比如認為 maxSize 代表是 KB 的話,那么就以 KB 為單位返回該項所占的內存大小。
除異常外首先會判斷 size 是否超過 maxSize,如果超過了就取出最先插入的緩存,如果不為空就刪掉,并把 size 減去該項所占的大小。這個操作將一直循環下去,直到 size 比 maxSize 小或者緩存為空。
public class LruCache<K, V> {
private final LinkedHashMap<K, V> map;//LinkedHashMap雙鏈表集合
/** Size of this cache in units. Not necessarily the number of elements. */
private int size;//內存占用大小
private int maxSize;//最大內存占用
private int putCount;//添加的次數
private int createCount;//創建的次數
private int evictionCount;//回收的次數
private int hitCount;//命中的次數
private int missCount;//丟失的次數
//記錄的次數沒有太大的意義,了解效率。
/**
* @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;
//LinkedHashMap是實現Lru算法的關鍵
//初始容量為0
//達到最大容量的75%時,會增加內存一半
//排序方式:true表示按訪問順序排序,訪問的值會被排在最后面,反之最前面是最近最少使用的值,flase表示按添加順序
this.map = new LinkedHashMap<K, V>(0, 0.75f, 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++;//添加次數+1
size += safeSizeOf(key, value);//計算value大小
previous = map.put(key, value);//添加進集合
//如果當前key的值存在,減去這條值得大小
if (previous != null) {
size -= safeSizeOf(key, previous);
}
}
//entryRemoved是一個空實現,如果我們使用LruCache的時候需要掌握元素移除的信息,可以重寫這個方法。
if (previous != null) {
entryRemoved(false, key, previous, value);
}
//整理內存空間,如果儲存空間(size)>最大儲存空間(maxSize),循環刪除最近最少使用的值
trimToSize(maxSize);
return previous;
}
//計算安全空間
private int safeSizeOf(K key, V value) {
int result = sizeOf(key, value);//sizeOf需要被重寫,返回實際的大小
if (result < 0) {
throw new IllegalStateException("Negative size: " + key + "=" + value);
}
return result;
}
//整理內存空間
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);
}
}
看完put
,那下面來看看get
:
public final V get(K key) {
if (key == null) {
throw new NullPointerException("key == null");
}
V mapValue;
synchronized (this) {
//根據kay獲取value值
mapValue = map.get(key);
//值存在
if (mapValue != null) {
hitCount++;//命中+1
return mapValue;
}
missCount++;//丟失+1
}
/*
* 值不存在,創建,如果值為null,則返回null
*/
V createdValue = create(key);
if (createdValue == null) {
return null;
}
//createdValue不為null
synchronized (this) {
createCount++;//創建+1
//添加新值進map
mapValue = map.put(key, createdValue);
//如果mapValue存在值,有沖突,所以撤消put操作
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;
}
}
最后說一下remove
方法:
public final V remove(K key) {
if (key == null) {
throw new NullPointerException("key == null");
}
V previous;
synchronized (this) {
//移除并獲取到返回的值
previous = map.remove(key);
//更新空間大小
if (previous != null) {
size -= safeSizeOf(key, previous);
}
}
if (previous != null) {
entryRemoved(false, key, previous, null);
}
return previous;
}