浅析LRUCache原理(Android)

  • LruCache类在调用get(K key) 方法时,都会调用LinkedHashMap.get(Object key) 。

  • 如上述设置了 accessOrder=true 后,调用LinkedHashMap.get(Object key) 都会通过LinkedHashMap的afterNodeAccess()方法将数据移到队尾。

  • 由于最新访问的数据在尾部,在 put 和 trimToSize 的方法执行下,如果发生数据移除,会优先移除掉头部数据

1.构造方法

/**

  • @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参数介绍:

  • initialCapacity 用于初始化该 LinkedHashMap 的大小。

  • loadFactor(负载因子)这个LinkedHashMap的父类 HashMap 里的构造参数,涉及到扩容问题,比如 HashMap 的最大容量是100,那么这里设置0.75f的话,到75的时候就会扩容。

  • accessOrder,这个参数是排序模式,true表示在访问的时候进行排序( LruCache 核心工作原理就在此),false表示在插入的时才排序。

2.添加数据 LruCache.put(K key, V value)

/**

  • 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++;

//safeSizeOf(key, value)。

//这个方法返回的是1,也就是将缓存的个数加1.

// 当缓存的是图片的时候,这个size应该表示图片占用的内存的大小,所以应该重写里面调用的sizeOf(key, value)方法

size += safeSizeOf(key, value);

//向map中加入缓存对象,若缓存中已存在,返回已有的值,否则执行插入新的数据,并返回null

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;

}

  • 开始的时候确实是把值放入LinkedHashMap,不管超不超过你设定的缓存容量。

  • 根据 safeSizeOf方法计算 此次添加数据的容量是多少,并且加到size 里 。

  • 方法执行到最后时,通过trimToSize()方法 来判断size 是否大于maxSize。

可以看到put()方法并没有太多的逻辑,重要的就是在添加过缓存对象后,调用 trimToSize()方法,来判断缓存是否已满,如果满了就要删除近期最少使用的数据。

2.trimToSize(int maxSize)

/**

  • 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) {

//如果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;

}

//在缓存队列中查找最近最少使用的元素,若不存在,直接退出循环,若存在则直接在map中删除。

Map.Entry<K, V> toEvict = map.eldest();

if (toEvict == null) {

break;

}

key = toEvict.getKey();

value = toEvict.getValue();

map.remove(key);

size -= safeSizeOf(key, value);

//回收次数+1

evictionCount++;

}

entryRemoved(true, key, value, null);

}

}

/**

  • Returns the eldest entry in the map, or {@code null} if the map is empty.

  • Android-added.

  • @hide

*/

public Map.Entry<K, V> eldest() {

Entry<K, V> eldest = header.after;

return eldest != header ? eldest : null;

}

trimToSize()方法不断地删除LinkedHashMap中队首的元素,即近期最少访问的,直到缓存大小小于最大值。

3.LruCache.get(K key)

/**

  • 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.

  • 通过key获取缓存的数据,如果通过这个方法得到的需要的元素,那么这个元素会被放在缓存队列的尾部,

*/

public final V get(K key) {

if (key == null) {

throw new NullPointerException(“key == null”);

}

V mapValue;

synchronized (this) {

//从LinkedHashMap中获取数据。

mapValue = map.get(key);

if (mapValue != null) {

hitCount++;

return mapValue;

}

missCount++;

}

/*

  • 正常情况走不到下面

  • 因为默认的 create(K key) 逻辑为null

  • 走到这里的话说明实现了自定义的create(K key) 逻辑,比如返回了一个不为空的默认值

*/

/*

  • 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

新的开始

改变人生,没有什么捷径可言,这条路需要自己亲自去走一走,只有深入思考,不断反思总结,保持学习的热情,一步一步构建自己完整的知识体系,才是最终的制胜之道,也是程序员应该承担的使命。

《系列学习视频》

《系列学习文档》

《我的大厂面试之旅》


《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!
开始

改变人生,没有什么捷径可言,这条路需要自己亲自去走一走,只有深入思考,不断反思总结,保持学习的热情,一步一步构建自己完整的知识体系,才是最终的制胜之道,也是程序员应该承担的使命。

《系列学习视频》
[外链图片转存中…(img-3n1TsEsz-1715334873213)]

《系列学习文档》

[外链图片转存中…(img-pcmTXy9j-1715334873213)]

《我的大厂面试之旅》

[外链图片转存中…(img-gQhGGywn-1715334873214)]
《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》点击传送门,即可获取!

  • 29
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值