浅析LRUCache原理(Android),附面试题答案

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

  • the map and release the created value.

  • 译:如果通过key从缓存集合中获取不到缓存数据,就尝试使用creat(key)方法创造一个新数据。

  • create(key)默认返回的也是null,需要的时候可以重写这个方法。

*/

V createdValue = create(key);

if (createdValue == null) {

return null;

}

//如果重写了create(key)方法,创建了新的数据,就讲新数据放入缓存中。

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;

}

}

自我介绍一下,小编13年上海交大毕业,曾经在小公司待过,也去过华为、OPPO等大厂,18年进入阿里一直到现在。

深知大多数Android工程师,想要提升技能,往往是自己摸索成长或者是报班学习,但对于培训机构动则几千的学费,着实压力不小。自己不成体系的自学效果低效又漫长,而且极易碰到天花板技术停滞不前!

因此收集整理了一份《2024年Android移动开发全套学习资料》,初衷也很简单,就是希望能够帮助到想自学提升又不知道该从何学起的朋友,同时减轻大家的负担。
img
img
img
img
img
img
img

既有适合小白学习的零基础资料,也有适合3年以上经验的小伙伴深入学习提升的进阶课程,基本涵盖了95%以上Android开发知识点,真正体系化!

由于文件比较大,这里只是将部分目录大纲截图出来,每个节点里面都包含大厂面经、学习笔记、源码讲义、实战项目、讲解视频,并且后续会持续更新

如果你觉得这些内容对你有帮助,可以添加V获取:vip204888 (备注Android)
img

面试复习笔记:

这份资料我从春招开始,就会将各博客、论坛。网站上等优质的Android开发中高级面试题收集起来,然后全网寻找最优的解答方案。每一道面试题都是百分百的大厂面经真题+最优解答。包知识脉络 + 诸多细节。
节省大家在网上搜索资料的时间来学习,也可以分享给身边好友一起学习。

《960页Android开发笔记》

《1307页Android开发面试宝典》

包含了腾讯、百度、小米、阿里、乐视、美团、58、猎豹、360、新浪、搜狐等一线互联网公司面试被问到的题目。熟悉本文中列出的知识点会大大增加通过前两轮技术面试的几率。

《507页Android开发相关源码解析》

只要是程序员,不管是Java还是Android,如果不去阅读源码,只看API文档,那就只是停留于皮毛,这对我们知识体系的建立和完备以及实战技术的提升都是不利的。

真正最能锻炼能力的便是直接去阅读源码,不仅限于阅读各大系统源码,还包括各种优秀的开源库。

链图片转存中…(img-I8Aw2ITC-1712029219149)]

《1307页Android开发面试宝典》

包含了腾讯、百度、小米、阿里、乐视、美团、58、猎豹、360、新浪、搜狐等一线互联网公司面试被问到的题目。熟悉本文中列出的知识点会大大增加通过前两轮技术面试的几率。

[外链图片转存中…(img-iPN3H2qG-1712029219150)]

《507页Android开发相关源码解析》

只要是程序员,不管是Java还是Android,如果不去阅读源码,只看API文档,那就只是停留于皮毛,这对我们知识体系的建立和完备以及实战技术的提升都是不利的。

真正最能锻炼能力的便是直接去阅读源码,不仅限于阅读各大系统源码,还包括各种优秀的开源库。

本文已被CODING开源项目:《Android学习笔记总结+移动架构视频+大厂面试真题+项目实战源码》收录

  • 3
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值