1. 概述
对于 Android 开发者,LruCache 肯定不陌生,几乎所有的图片缓存框架都会用到它来实现内存缓存等,可见 LruCache 在 Android 开发中的重要性。LRU 是 Least Recently Used 的缩写,近期最少使用的意思。当我们进行缓存的时候,如果缓存满了,会先淘汰使用最少的缓存对象。因为在 Android 中为每个APP分配的内存大小有限,而 LruCache 的使用,可以为缓存指定固定大小的空间,当缓存大小超过这个空间,就会优先淘汰最少使用的缓存对象,从而避免因为缓存对象太大造成的内存溢出。
2. LruCache 的使用
// 设置LruCache缓存的大小,一般为当前进程可用容量的1/8
int cacheSize = (int) (Runtime.getRuntime().totalMemory() / 8);
LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>(cacheSize) {
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes() * value.getHeight() / 1024;
}
};
lruCache.put("key", bitmap);
Bitmap value = lruCache.get("key");
这是 LruCache 基本的用法:指定缓存的大小,当超出指定的大小后会进行回收最小的缓存对象,重写 sizeOf 方法,返回每个存储对象的大小,为何要重写 sizeOf 方法,后面会进行说明。调用 put、get 方法实现从 LruCache 中存储和取出对象。
3. 源码解析
LruCache 是一个泛型类,并没有任何的父类以及实现任何的接口:
public class LruCache<K, V> {
...
...
}
3.1 主要变量
private final LinkedHashMap<K, V> map; //LruCache 内部靠 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;
3.2 构造方法
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);
}
在此构造方法中,传入 LruCache 允许存储的最大容量 maxSize,如果传入的 maxSize 小于0,则直接抛出异常。初始化LinkedHashMap 对象,调用的是 LinkedHashMap 三个参数的构造方法,最后一个参数代表 LinkedHashMap 是否进行访问排序。对于 LinkedHashMap 的解析可以看 LinkedHashMap 源码解析。
3.3 put 方法
public final V put(K key, V value) {
if (key == null || value == null) { //1
throw new NullPointerException("key == null || value == null");
}
V previous;
synchronized (this) {
putCount++; //2
size += safeSizeOf(key, value); //3
previous = map.put(key, value); //4
if (previous != null) { //5
size -= safeSizeOf(key, previous);
}
}
if (previous != null) { //6
entryRemoved(false, key, previous, value);
}
trimToSize(maxSize);//7
return previous;
}
注释1 中,LruCache 是不允许 key 和 value 中任何一个为 null,否则抛出空指针异常。
注释2 中,putCount 的值增加1,记录存储的次数。
注释3 中,size 在原来的基础加上方法 safeSizeOf 返回值,size 存储当前存储的缓存大小。
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(key, value)。
sizeOf:
protected int sizeOf(K key, V value) {
return 1;
}
默认的方法返回值 1,如果每次返回的都是1,而 size 只增加1。如果在初始化 LruCache 对象时候不重写此方法,并返回每个存储对象的大小,构造方法传入的 maxSize 只有用来记录存储的最大个数。如果重写此方法,并返回了每个存储对象的大小,则 maxSize 则表示存储的对象的最大容量。这里 sizeOf 返回值的单位要和构造方法中传入参数的单位一致才有意义,比如大小都字节等。
再回到 put 方法中:
注释 4 ,调用 LinkedHashMap 中的 put 方法,并将返回值赋值给临时变量:V previous;
注释5 ,如果 previous 不为空,则表示已经有此缓存对象,则必须把注释3 中加入的大小再次扣除,将缓存大小恢复到之前。
注释6 ,如果 previous 不为空,则表示已经有此缓存对象,则调用方法 entryRemoved,方法 entryRemoved 为空方法,如果有需要进行重写。
protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) {}
注释7,调用方法 trimToSize,传入的参数为允许存储的最大容量,此方法用于调整缓存大小,来判断缓存是否已满,如果满了就要删除近期最少使用的对象。下面将对方法 trimToSize 进行解释。
最后,put 方法返回的是 previous 对象。
3.4 trimToSize 方法
用 AndroidStudio 追踪源码的方式,LruCache 的 trimToSize 方法如下:
private 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;
}
// BEGIN LAYOUTLIB CHANGE
// get the last item in the linked list.
// This is not efficient, the goal here is to minimize the changes
// compared to the platform version.
Map.Entry<K, V> toEvict = null;
for (Map.Entry<K, V> entry : map.entrySet()) { //8
toEvict = entry;
}
// END LAYOUTLIB CHANGE
if (toEvict == null) {
break;
}
key = toEvict.getKey();
value = toEvict.getValue();
map.remove(key); //9
size -= safeSizeOf(key, value);
evictionCount++;
}
entryRemoved(true, key, value, null);
}
}
在此方法中,是一个 while 的死循环。在此循环中如果当前存储的大小 size 如果比指定的最大缓存大小还小,则跳出死循环。否则继续执行。
注释8 中,取出 LinkedHashMap 中队尾的元素,并赋值给临时变量 Map.Entry<K, V> toEvict。(Android Stuido 方式追踪的源码,这里存在着问题,搞得我怀疑人生)
真正的代码应该如下:
http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/java/android/util/LruCache.java#trimToSize
toEvict 应该为 eldest 方法的返回值:
public Map.Entry<K, V> eldest() {
return head;
}
取出的应该是 LinkedHashMap 中链表头部的元素。
注释9 中,调用 remove 方法,用于将 LinkedHashMap 中头部的对象进行移除,并且将存储大小 (size) 的值减去移除的对象的大小。 evictionCount 值加1。
不断的进行死循环,直到最后 size 的值小于 maxSize。
3.5 get 方法
public final V get(K key) {
if (key == null) { //10
throw new NullPointerException("key == null");
}
V mapValue;
synchronized (this) {
mapValue = map.get(key); //11
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.
*/
V createdValue = create(key); //12
if (createdValue == null) {
return null;
}
synchronized (this) {
createCount++;
mapValue = map.put(key, createdValue);
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;
}
}
注释10,如果 key 为空,则抛出空指针异常。
注释11,从 LinkedHashMap 中取出元素,如果不为空则返回。如果 LinkedHashMap 中不存在这个值,则新建一个这样的值,但是新建的方法 create 是空方法,除非进行重写。
protected V create(K key) {
return null;
}
4. 总结
从以上的分析可以得出:
LruCache 底层是一个 LinkedHashMap 作为存储,在初始化 LruCache 对象时候,需要进行指定最大的缓存大小,并重写 sieOf 方法用于计算每次存储的对象大小。如果不重写 sieOf 方法,则初始化时候指定的为可存储的个数。当调用 put 方法存储对象时候,会判断当前缓存的大小是否小于指定的最大缓存,如果当前缓存的不小于指定最大缓存,则会调用 trimToSize 方法进行清理最早访问的对象,即 LinkedHashMap 头部的元素, 直到当前缓存大小小于指定的最大缓存大小。当调用 get 方法时候,则调用的 LinkedHashMap 的 get 方法,LinkedHashMap 会将访问的对象移动到链表的尾部,为 trimToSize 中清理最早访问的对象(链表头部的元素) 做准备。
已经是8号的1点30分,睡了,晚安!
附上 Lrucache 的源码:
http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/java/android/util/LruCache.java#trimToSize
/*
* Copyright (C) 2011 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package android.util;
import java.util.LinkedHashMap;
import java.util.Map;
/**
* A cache that holds strong references to a limited number of values. Each time
* a value is accessed, it is moved to the head of a queue. When a value is
* added to a full cache, the value at the end of that queue is evicted and may
* become eligible for garbage collection.
*
* <p>If your cached values hold resources that need to be explicitly released,
* override {@link #entryRemoved}.
*
* <p>If a cache miss should be computed on demand for the corresponding keys,
* override {@link #create}. This simplifies the calling code, allowing it to
* assume a value will always be returned, even when there's a cache miss.
*
* <p>By default, the cache size is measured in the number of entries. Override
* {@link #sizeOf} to size the cache in different units. For example, this cache
* is limited to 4MiB of bitmaps:
* <pre> {@code
* int cacheSize = 4 * 1024 * 1024; // 4MiB
* LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) {
* protected int sizeOf(String key, Bitmap value) {
* return value.getByteCount();
* }
* }}</pre>
*
* <p>This class is thread-safe. Perform multiple cache operations atomically by
* synchronizing on the cache: <pre> {@code
* synchronized (cache) {
* if (cache.get(key) == null) {
* cache.put(key, value);
* }
* }}</pre>
*
* <p>This class does not allow null to be used as a key or value. A return
* value of null from {@link #get}, {@link #put} or {@link #remove} is
* unambiguous: the key was not in the cache.
*
* <p>This class appeared in Android 3.1 (Honeycomb MR1); it's available as part
* of <a href="http://developer.android.com/sdk/compatibility-library.html">Android's
* Support Package</a> for earlier releases.
*/
public class LruCache<K, V> {
private final LinkedHashMap<K, V> map;
/** 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;
this.map = new LinkedHashMap<K, V>(0, 0.75f, true);
}
/**
* Sets the size of the cache.
*
* @param maxSize The new maximum size.
*/
public void resize(int maxSize) {
if (maxSize <= 0) {
throw new IllegalArgumentException("maxSize <= 0");
}
synchronized (this) {
this.maxSize = maxSize;
}
trimToSize(maxSize);
}
/**
* Returns the value for {@code key} if it exists in the cache or can be
* created by {@code #create}. If a value was returned, it is moved to the
* head of the queue. This returns null if a value is not cached and cannot
* be created.
*/
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.
*/
V createdValue = create(key);
if (createdValue == null) {
return null;
}
synchronized (this) {
createCount++;
mapValue = map.put(key, createdValue);
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;
}
}
/**
* Caches {@code value} for {@code key}. The value is moved to the head of
* the queue.
*
* @return the previous value mapped by {@code key}.
*/
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 += safeSizeOf(key, value);
previous = map.put(key, value);
if (previous != null) {
size -= safeSizeOf(key, previous);
}
}
if (previous != null) {
entryRemoved(false, key, previous, value);
}
trimToSize(maxSize);
return previous;
}
/**
* Remove the eldest entries until the total of remaining entries is at or
* below the requested size.
*
* @param maxSize the maximum size of the cache before returning. May be -1
* to evict even 0-sized elements.
*/
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);
}
}
/**
* Removes the entry for {@code key} if it exists.
*
* @return the previous value mapped by {@code key}.
*/
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;
}
/**
* Called for entries that have been evicted or removed. This method is
* invoked when a value is evicted to make space, removed by a call to
* {@link #remove}, or replaced by a call to {@link #put}. The default
* implementation does nothing.
*
* <p>The method is called without synchronization: other threads may
* access the cache while this method is executing.
*
* @param evicted true if the entry is being removed to make space, false
* if the removal was caused by a {@link #put} or {@link #remove}.
* @param newValue the new value for {@code key}, if it exists. If non-null,
* this removal was caused by a {@link #put}. Otherwise it was caused by
* an eviction or a {@link #remove}.
*/
protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) {}
/**
* Called after a cache miss to compute a value for the corresponding key.
* Returns the computed value or null if no value can be computed. The
* default implementation returns null.
*
* <p>The method is called without synchronization: other threads may
* access the cache while this method is executing.
*
* <p>If a value for {@code key} exists in the cache when this method
* returns, the created value will be released with {@link #entryRemoved}
* and discarded. This can occur when multiple threads request the same key
* at the same time (causing multiple values to be created), or when one
* thread calls {@link #put} while another is creating a value for the same
* key.
*/
protected V create(K key) {
return null;
}
private int safeSizeOf(K key, V value) {
int result = sizeOf(key, value);
if (result < 0) {
throw new IllegalStateException("Negative size: " + key + "=" + value);
}
return result;
}
/**
* Returns the size of the entry for {@code key} and {@code value} in
* user-defined units. The default implementation returns 1 so that size
* is the number of entries and max size is the maximum number of entries.
*
* <p>An entry's size must not change while it is in the cache.
*/
protected int sizeOf(K key, V value) {
return 1;
}
/**
* Clear the cache, calling {@link #entryRemoved} on each removed entry.
*/
public final void evictAll() {
trimToSize(-1); // -1 will evict 0-sized elements
}
/**
* For caches that do not override {@link #sizeOf}, this returns the number
* of entries in the cache. For all other caches, this returns the sum of
* the sizes of the entries in this cache.
*/
public synchronized final int size() {
return size;
}
/**
* For caches that do not override {@link #sizeOf}, this returns the maximum
* number of entries in the cache. For all other caches, this returns the
* maximum sum of the sizes of the entries in this cache.
*/
public synchronized final int maxSize() {
return maxSize;
}
/**
* Returns the number of times {@link #get} returned a value that was
* already present in the cache.
*/
public synchronized final int hitCount() {
return hitCount;
}
/**
* Returns the number of times {@link #get} returned null or required a new
* value to be created.
*/
public synchronized final int missCount() {
return missCount;
}
/**
* Returns the number of times {@link #create(Object)} returned a value.
*/
public synchronized final int createCount() {
return createCount;
}
/**
* Returns the number of times {@link #put} was called.
*/
public synchronized final int putCount() {
return putCount;
}
/**
* Returns the number of values that have been evicted.
*/
public synchronized final int evictionCount() {
return evictionCount;
}
/**
* Returns a copy of the current contents of the cache, ordered from least
* recently accessed to most recently accessed.
*/
public synchronized final Map<K, V> snapshot() {
return new LinkedHashMap<K, V>(map);
}
@Override public synchronized final String toString() {
int accesses = hitCount + missCount;
int hitPercent = accesses != 0 ? (100 * hitCount / accesses) : 0;
return String.format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]",
maxSize, hitCount, missCount, hitPercent);
}
}