Android缓存机制——LruCache的详解
作者:Android高级架构 发布时间:2023-07-30 07:26:34
概述
LruCache的核心原理就是对LinkedHashMap的有效利用,它的内部存在一个LinkedHashMap成员变量,值得注意的4个方法:构造方法、get、put、trimToSize
LRU(Least Recently Used)缓存算法便应运而生,LRU是最近最少使用的算法,它的核心思想是当缓存满时,会优先淘汰那些最近最少使用的缓存对象。采用LRU算法的缓存有两种:LrhCache和DisLruCache,分别用于实现内存缓存和硬盘缓存,其核心思想都是LRU缓存算法。
LRU原理
LruCache的核心思想很好理解,就是要维护一个缓存对象列表,其中对象列表的排列方式是按照访问顺序实现的,即一直没访问的对象,将放在队头,即将被淘汰。而最近访问的对象将放在队尾,最后被淘汰。(队尾添加元素,队头删除元素)
LruCache 其实使用了 LinkedHashMap 双向链表结构,现在分析下 LinkedHashMap 使用方法。
1.构造方法:
public LinkedHashMap(int initialCapacity,
float loadFactor,
boolean accessOrder) {
super(initialCapacity, loadFactor);
this.accessOrder = accessOrder;
}
当 accessOrder 为 true 时,这个集合的元素顺序就会是访问顺序,也就是访问了之后就会将这个元素放到集合的最后面。
例如:
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.get(1);
map.get(2);
for (Map.Entry < Integer, Integer > entry: map.entrySet()) {
System.out.println(entry.getKey() + ":" + entry.getValue());
}
输出结果:
0:0
3:3
1:1
2:2
下面我们在LruCache源码中具体看看,怎么应用LinkedHashMap来实现缓存的添加,获得和删除的:
/**
* @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);//accessOrder被设置为true
}
从LruCache的构造函数中可以看到正是用了LinkedHashMap的访问顺序。
2.put()方法
/**
* 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++;//插入缓存对象加1
size += safeSizeOf(key, value);//增加已有缓存的大小
previous = map.put(key, value);//向map中加入缓存对象
if (previous != null) {//如果已有缓存对象,则缓存大小恢复到之前
size -= safeSizeOf(key, previous);
}
}
if (previous != null) {//entryRemoved()是个空方法,可以自行实现
entryRemoved(false, key, previous, value);
}
trimToSize(maxSize);//调整缓存大小(关键方法)
return previous;
}
可以看到put()方法重要的就是在添加过缓存对象后,调用 trimToSize()方法来保证内存不超过maxSize
3.trimToSize方法
再看一下trimToSize()方法:
/**
* 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小于最大缓存,或者map为空,不需要再删除缓存对象,跳出循环
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);
evictionCount++;
}
entryRemoved(true, key, value, null);
}
}
trimToSize()方法不断地删除LinkedHashMap中队头的元素,即近期最少访问的,直到缓存大小小于最大值。
4. get方法
当调用LruCache的get()方法获取集合中的缓存对象时,就代表访问了一次该元素,将会更新队列,保持整个队列是按照访问顺序排序。这个更新过程就是在LinkedHashMap中的get()方法中完成的。
接着看LruCache的get()方法
/**
* 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) {//key不能为空
throw new NullPointerException("key == null");
}
V mapValue;
synchronized (this) {
/获取对应的缓存对象
mapValue = map.get(key);
if (mapValue != null) {
hitCount++;
return mapValue;
}
missCount++;
}
看到LruCache的get方法实际是调用了LinkedHashMap的get方法:
public V get(Object key) {
LinkedHashMapEntry<K,V> e = (LinkedHashMapEntry<K,V>)getEntry(key);
if (e == null)
return null;
e.recordAccess(this);//实现排序的关键
return e.value;
}
再接着看LinkedHashMapEntry的recordAccess方法:
/**
* This method is invoked by the superclass whenever the value
* of a pre-existing entry is read by Map.get or modified by Map.set.
* If the enclosing Map is access-ordered, it moves the entry
* to the end of the list; otherwise, it does nothing.
*/
void recordAccess(HashMap<K,V> m) {
LinkedHashMap<K,V> lm = (LinkedHashMap<K,V>)m;
if (lm.accessOrder) {//判断是否是访问顺序
lm.modCount++;
remove();//删除此元素
addBefore(lm.header);//将此元素移到队尾
}
}
recordAccess方法的作用是如果accessOrder为true,把已存在的entry在调用get读取或者set编辑后移到队尾,否则不做任何操作。
也就是说: 这个方法的作用就是将刚访问过的元素放到集合的最后一位
总结:
LruCache的核心原理就是对LinkedHashMap 对象的有效利用。在构造方法中设置maxSize并将accessOrder设为true,执行get后会将访问元素放到队列尾,put操作后则会调用trimToSize维护LinkedHashMap的大小不大于maxSize。
以上所述是小编给大家介绍的Android缓存机制LruCache详解整合,希望对大家有所帮助
来源:https://blog.csdn.net/weixin_44941011/article/details/89818050
猜你喜欢
- 注意是maven的webapp:选择maven下一步下一步。maven下载过慢在setting中加入镜像。 我也有疑问这是什么鬼格式,但是证
- 模拟登陆的原理很简单,就是发送一个Http 请求服务器获得响应,然后客户端获取到cookie即可实现模拟登陆,比如一些抢票软件的原理无非也是
- 报错翻译: compileSdkVersion android-24”需要JDK 1.8或更高版本编译。报错现象如下图:原因:st
- 一:问题描述 在已经root过的android设备下,app执行一个linux命令,app需要获取su权限,在某些a
- 已知两个链表list1和list,2,各自非降序排列,将它们合并成另外一个链表list3,并且依然有序,要求保留所有节点。实现过程中,lis
- 1.map遍历快速实现边距,文字自适应改变大小Container( // padding: EdgeI
- Android 中ScrollView嵌套GridView,ListView的实例在Android开发中,经常有一些UI需要进行固定styl
- 在style中如下面那样定义:<style name="mystyle"> <item name=&
- 格式要求:SU MO TU WE TH FR SA &nb
- AlertDialog可以在当前的界面上显示一个对话框,这个对话框是置顶于所有界面元素之上的,能够屏蔽掉其他控件的交互能力,因此AlertD
- 一、整体设计1、需求分析池化技术是计算机中的一种设计模式,内存池是常见的池化技术之一,它能够有效的提高内存的申请和释放效率以及内存碎片等问题
- 1)打开idea,开始创建SpringBoot项目2)选择 Spring Initializr ,选择合适的jdk版本,点击Next在操作到
- 开篇语Synchronized,Java 友好的提供了的一个关键字,它让开发者可以快速的实现同步。它就像一个星星,远远看去就是一个小小的点。
- 1.根据单个分隔字符用split截取例如string st="GT123_1";string[] sArray=st.s
- 目录前言1. 不受待见的空指针异常2. 糟糕的代码3. 解决空指针的"银弹"4. Optional使用入门(1)创建Op
- 前言为什么用动静态库我们在实际开发中,经常要使用别人已经实现好的功能,这是为了开发效率和鲁棒性(健壮性);因为那些功能都是顶尖的工程师已经写
- 一、导入和导出导入:通过解析excel表格中的数据,然后将数据放到一个集合中,接着通过对持久层操作,将数据插入到数据库中,再加载一下页面,从
- 本文实例讲述了Android编程之消息机制。分享给大家供大家参考,具体如下:一、角色描述1.Looper: 一个线程可以产生一个Looper
- 什么是RecyclerView关于RecyclerView,是一个主要用于展示和回收View的有一个控件,在官用了一句话来概括Recycle
- 自定义 webflux 容器配置配置代码@Componentpublic class ContainerConfig extends Rea