LruCache,首先从名字就能够看出它的功能。做为较为经常使用的缓存策略,它在平常开发中起到了重要的做用。例如Glide中,它与SoftReference 在Engine类中缓存图片,能够减小流量开销,提高加载图片的效率。在API12时引入android.util.LruCache,然而在API22时对它进行了修改,引入了android.support.v4.util.LruCache。咱们在这里分析的是support包里的LruCachejava
Lru(Least Recently Used),也就是最近最少使用算法。它在内部维护了一个LinkedHashMap,在put数据的时候会判断指定的内存大小是否已满。若已满,则会使用最近最少使用算法进行清理。至于为何要使用LinkedHashMap存储,由于LinkedHashMap内部是一个数组加双向链表的形式来存储数据,也就是说当咱们经过get方法获取数据的时候,数据会从队列跑到队头来。反反复复,队尾的数据天然是最少使用到的数据。
node
通常来讲,咱们都是取运行时最大内存的八分之一来做为内存空间,同时还要覆写一个sizeOf的方法。特别须要强调的是,sizeOf的单位必须和内存空间的单位一致。android
int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024);
LruCache<String, Bitmap> cache = new LruCache<String, Bitmap>(maxMemory / 8) {
@Override
protected int sizeOf(@NonNull String key, @NonNull Bitmap value) {
return bitmap.getRowBytes() * bitmap.getHeight() / 1024;
}
};
复制代码
公共方法 | |
---|---|
final int |
createCount() 返回返回值的次数create(Object) 。 |
final void |
evictAll() 清除缓存,调用entryRemoved(boolean, K, V, V) 每一个删除的条目。 |
final int |
evictionCount() 返回已被驱逐的值的数量。 |
final V |
get(K key) 返回key 缓存中是否存在的值,仍是能够建立的值#create 。 |
final int |
hitCount() 返回返回get(K) 已存在于缓存中的值的次数。 |
final int |
maxSize() 对于不覆盖的高速缓存sizeOf(K, V) ,这将返回高速缓存中的最大条目数。 |
final int |
missCount() 返回get(K) 返回null或须要建立新值的次数。 |
final V |
put(K key, V value) 缓存value 的key 。 |
final int |
putCount() 返回put(K, V) 调用的次数。 |
final V |
remove(K key) 删除条目(key 若是存在)。 |
void |
resize(int maxSize) 设置缓存的大小。 |
final int |
size() 对于不覆盖的高速缓存sizeOf(K, V) ,这将返回高速缓存中的条目数。 |
final Map<K, V> |
snapshot() 返回缓存的当前内容的副本,从最近最少访问到最近访问的顺序排序。 |
final String |
toString() |
void |
trimToSize(int maxSize) 删除最旧的条目,直到剩余条目的总数等于或低于请求的大小。 |
咱们接下里从构造方法开始为你们进行讲解:算法
public LruCache(int maxSize) {
if (maxSize <= 0) {
throw new IllegalArgumentException("maxSize <= 0");
} else {
this.maxSize = maxSize;
this.map = new LinkedHashMap(0, 0.75F, true);
}
}
复制代码
构造函数一共作了两件事。第一节:判断maxSize是否小于等于0。第二件,初始化maxSize和LinkedHashMap。没什么可说的,咱们接着往下走。数组
private int safeSizeOf(K key, V value) {
int result = this.sizeOf(key, value);
if (result < 0) {//判空
throw new IllegalStateException("Negative size: " + key + "=" + value);
} else {
return result;
}
}
复制代码
这个方法必定要覆写,不然存不进数据。缓存
protected int sizeOf(@NonNull K key, @NonNull V value) {
return 1;
}
复制代码
@Nullable
public final V put(@NonNull K key, @NonNull V value) {
if (key != null && value != null) {
Object previous;
synchronized(this) {
++this.putCount;//count为LruCahe的缓存个数,这里加一
this.size += this.safeSizeOf(key, value);//加上这个value的大小
previous = this.map.put(key, value);//存进LinkedHashMap中
if (previous != null) {//若是以前存过这个key,则减掉以前value的大小
this.size -= this.safeSizeOf(key, previous);
}
}
if (previous != null) {
this.entryRemoved(false, key, previous, value);
}
this.trimToSize(this.maxSize);//进行内存判断
return previous;
} else {
throw new NullPointerException("key == null || value == null");
}
}
复制代码
在synchronized代码块里,进入的就是一次插入操做。咱们往下,俺老孙定眼一看,彷佛trimToSize这个方法有什么不寻常的地方?数据结构
public void trimToSize(int maxSize) {
while(true) {//这是一个无限循环,目的是为了移除value直到内存空间不溢出
Object key;
Object value;
synchronized(this) {
if (this.size < 0 || this.map.isEmpty() && this.size != 0) {//若是没有分配内存空间,抛出异常
throw new IllegalStateException(this.getClass().getName() + ".sizeOf() is reporting inconsistent results!");
}
if (this.size <= maxSize || this.map.isEmpty()) {//若是小于内存空间,just so so~
return;
}
//不然将使用Lru算法进行移除
Entry<K, V> toEvict = (Entry)this.map.entrySet().iterator().next();
key = toEvict.getKey();
value = toEvict.getValue();
this.map.remove(key);
this.size -= this.safeSizeOf(key, value);
++this.evictionCount;//回收次数+1
}
this.entryRemoved(true, key, value, (Object)null);
}
}
复制代码
这个TrimToSize方法的做用在于判断内存空间是否溢出。利用无限循环,将一个一个的最少使用的数据给剔除掉。ide
@Nullable
public final V get(@NonNull K key) {
if (key == null) {
throw new NullPointerException("key == null");
} else {
Object mapValue;
synchronized(this) {
mapValue = this.map.get(key);
if (mapValue != null) {
++this.hitCount;//命中次数+1,而且返回mapValue
return mapValue;
}
++this.missCount;//未命中次数+1
}
/* 若是未命中,会尝试利用create方法建立对象 create须要本身实现,若未实现则返回null */
V createdValue = this.create(key);
if (createdValue == null) {
return null;
} else {
synchronized(this) {
//建立了新对象以后,再将其添加进map中,与以前put方法逻辑基本相同
++this.createCount;
mapValue = this.map.put(key, createdValue);
if (mapValue != null) {
this.map.put(key, mapValue);
} else {
this.size += this.safeSizeOf(key, createdValue);
}
}
if (mapValue != null) {
this.entryRemoved(false, key, createdValue, mapValue);
return mapValue;
} else {
this.trimToSize(this.maxSize);//每次加入数据时,都须要判断一下是否溢出
return createdValue;
}
}
}
}
复制代码
@Nullable
protected V create(@NonNull K key) {
return null;//这个方法须要本身实现
}
复制代码
get方法和create方法的注释已经写在了代码上,这里逻辑一样不是很复杂。可是咱们须要注意的是map的get方法,既然LinkedHashMap能实现Lru算法,那么它的内部必定不简单!函数
public V get(Object key) {
Node<K,V> e;
if ((e = getNode(hash(key), key)) == null)
return null;
if (accessOrder)
afterNodeAccess(e);
return e.value;
}
复制代码
LinkedHashMap中,首先进行了判断,是否找到该元素,没找到则返回null。找到则调用afterNodeAccess方法。源码分析
void afterNodeAccess(Node<K,V> e) { // move node to last
LinkedHashMapEntry<K,V> last;
//accessOrder为true 且当前节点不是尾节点 则按访问顺序排序
if (accessOrder && (last = tail) != e) {
LinkedHashMapEntry<K,V> p =
(LinkedHashMapEntry<K,V>)e, b = p.before, a = p.after;
//下面是排序过程
p.after = null;
if (b == null)
head = a;
else
b.after = a;
if (a != null)
a.before = b;
else
last = b;
if (last == null)
head = p;
else {
p.before = last;
last.after = p;
}
tail = p;
++modCount;
}
}
复制代码
原来如此!LinkedHashMap在这个方法中实现了按访问顺序排序,这也就是为何咱们的LruCache底层是使用的LinkedHashMap做为数据结构。
主要方法已经讲完了 ,接下里咱们就看看其余方法吧。
@Nullable
public final V remove(@NonNull K key) {
if (key == null) {//判空
throw new NullPointerException("key == null");
} else {
Object previous;
synchronized(this) {
previous = this.map.remove(key);//根据key移除value
if (previous != null) {
this.size -= this.safeSizeOf(key, previous);//减掉value的大小
}
}
if (previous != null) {
this.entryRemoved(false, key, previous, (Object)null);
}
return previous;
}
}
复制代码
public final void evictAll() {
this.trimToSize(-1);//移除掉全部的value
}
复制代码
public final synchronized int size() {
return this.size;//当前内存空间的size
}
public final synchronized int maxSize() {
return this.maxSize;//内存空间最大的size
}
public final synchronized int hitCount() {
return this.hitCount;//命中个数
}
public final synchronized int missCount() {
return this.missCount;//未命中个数
}
public final synchronized int createCount() {
return this.createCount;//建立Value的个数
}
public final synchronized int putCount() {
return this.putCount;//put进去的个数
}
public final synchronized int evictionCount() {
return this.evictionCount;//移除个数
}
public final synchronized Map<K, V> snapshot() {
return new LinkedHashMap(this.map);//建立LinkedHashMap
}
public final synchronized String toString() {//toString
int accesses = this.hitCount + this.missCount;
int hitPercent = accesses != 0 ? 100 * this.hitCount / accesses : 0;
return String.format(Locale.US, "LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]", this.maxSize, this.hitCount, this.missCount, hitPercent);
}
复制代码
有了这篇文章,相信你们对LruCache的工做原理已经很清楚了吧!有什么不对的地方但愿你们可以指正。学无止境,你们一块儿加油吧。