LruCache 里面最要有几个重要因素
- 设置LruCache缓存的大小,一般为当前进程可用容量的1/8
- 重写sizeOf方法,计算出要缓存的每张图片的大小
int maxMemory = (int) (Runtime.getRuntime().totalMemory()/1024);
int cacheSize = maxMemory/8;
mMemoryCache = new LruCache<String,Bitmap>(cacheSize){
@Override
protected int sizeOf(String key, Bitmap value) {
return value.getRowBytes()*value.getHeight()/1024;
}
};
- 最近最少使用算法
- 最近最少使用算法的实现是通过LinkedHashMap来实现的,没有软引用,都是强引用
- 如果添加的数据大于设置的最大值,就删除最先缓存的数据来调整内存。他的主要原理在trimToSize方法中
LinkedHashMap
- LinkedHashMap继承于HashMap,它使用了一个双向链表来存储Map中的Entry顺序关系,
- 这种顺序有两种,一种是LRU顺序,一种是插入顺序,可通过构造方法设置
- LRU顺序(访问顺序:表示双向链表中的元素按照访问的先后顺序排列):get时将该对象移到链表的尾部,put插入新的对象也是存储在链表的尾部,这样当内存缓存达到设定的最大值时,将链表头部的对象(最近最少用到的)移除,
- 插入顺序:是按照插入的顺序实现的,put时插入新的对象是存储在链表的尾部,就是当标志位accessOrder的值为false时
设置LinkedHashMap的存储顺序
通过构造方法进行指定
public LinkedHashMap(int initialCapacity,
float loadFactor,
boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder;
}
其中accessOrder设置为true则为访问顺序,为false,则为插入顺序
例子:当设置为true时
public static final void main(String[] args) {
LinkedHashMap<Integer, Integer> map = new LinkedHashMap<>(0, 0.75f, true);
map.put(0, 0);
map.put(1, 1);
map.put(2, 2);
map.put(3, 3);
map.put(4, 4);
map.put(5, 5);
map.put(6, 6);
map.get(1);
map.get(2);
for (Map.Entry<Integer, Integer> entry : map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
}
输出结果:
0:0
3:3
4:4
5:5
6:6
1:1
2:2
这就最近最少使用算法的顺序(访问顺序)
LruCache是用作缓存,既然涉及到了缓存必定有put、get 方法,接下来就看下LruCache 中的put和get方法
LruCache中的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) {
//插入的缓存对象值加1
putCount++;
//增加已有缓存的大小
size += safeSizeOf(key, value);
//向map中加入缓存对象
previous = map.put(key, value);
//如果已有缓存对象,则缓存大小恢复到之前
if (previous != null) {
size -= safeSizeOf(key, previous);
}
}
//entryRemoved()是个空方法,可以自行实现
if (previous != null) {
entryRemoved(false, key, previous, value);
}
//调整缓存大小(关键方法)
trimToSize(maxSize);
return previous;
}
关键点是在调用了put方法中还执行了trimToSize()方法,作用是判断缓存大小是否够用,如果不够需要先删除近期少访问的元素
看下trimToSize()方法
public void trimToSize(int maxSize) {
while (true) {
K key;
V value;
synchronized (this) {
//如果map为空并且缓存size不等于0或者缓存size小于0,抛出异常
if (size < 0 || (map.isEmpty() && size != 0)) {
throw new IllegalStateException(getClass().getName()
+ ".sizeOf() is reporting inconsistent results!");
}
//如果缓存大小size小于最大缓存,不需要再删除缓存对象,跳出循环
if (size <= maxSize) {
break;
}
//获取head,近期最少访问的元素
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);
}
}
LruCache 中的 get() 方法
public final V get(K key) {
if (key == null) {
throw new NullPointerException("key == null");
}
V mapValue;
synchronized (this) {
//获取对应的缓存对象
//LinkedHashMap 的 get()方法会实现将访问的元素更新到队列尾部的功能
mapValue = map.get(key);
mapValue = map.get(key);
if (mapValue != null) {
hitCount++;
return mapValue;
}
missCount++;
}
//省略
}
进入LinkedHashMap的get()方法
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的原理