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
![](https://www.aspxhome.com/images/zang.png)
![](https://www.aspxhome.com/images/jiucuo.png)
猜你喜欢
- FileWriter/FileReader介绍:FileWriter 类从 OutputStreamWriter 类继承而来。该类按字符向流
- /** * 实现 * @author dujinyang * */顺序是: OneAcitivity
- 每一个基于java的应用程序都有一个共同工作来展示给用户看到的内容作为工作的应用几个对象。当编写一个复杂的Java应用程序,应用程序类应该尽
- protected 来谈谈protected访问权限问题。看下面示例1:Test.javaclass MyObject {}public c
- 本文实例所述为Android天气预报之解析天气数据的代码,可实现获取HttpGet对象读取天气网站天气数据,并从数据中解析出天气数据,比如温
- 一、背景今天有小伙伴面试的时候被问到:Spring AOP中JDK 和 CGLib * 哪个效率更高?二、基本概念首先,我们知道Sprin
- 前言但是没有合理的架构,大家写出来的代码很可能是一大堆的复制粘贴。比如十几个页面,都有这个关注按钮。然后,你是不是也要写十几个地方呢 然后修
- 前言static和final是两个我们必须掌握的关键字。不同于其他关键字,他们都有多种用法,而且在一定环境下使用,可以提高程序的运行性能,优
- 概述递归:指在当前方法内调用自己的这种现象。递归的分类:递归分为两种,直接递归和间接递归。直接递归称为方法自身调用自己。间接递归可以A方法调
- 今天学习到了SpringBoot 的属性赋值@Value用法先总结@Value(" 张三 "):直接附在属性名上,在Be
- 当前比较成熟一点的应用基本上都会在进入应用之显示一个启动界面.这个启动界面或简单,或复杂,或简陋,或华丽,用意不同,风格也不同.下面来观摩几
- 前言最近遇到很有意思转换二进制的问题,有部分童鞋俨然已了解,可能也有一部分童鞋没碰到过也就不知情,这里我们来深入学习下转换二进制所带来的问题
- 项目地址:https://github.com/JeasonWong/SlackLoadingView老规矩,先上效果。图好大。。说下第一眼
- 前言:在 Java 中,让线程休眠的方法有很多,这些方法大致可以分为两类,一类是设置时间,在一段时间后自动唤醒,而另一个类是提供了一对休眠和
- public void ProcessRequest (HttpContext context) { &n
- 本文实例讲述了C#实现3步手动建DataGridView的方法。分享给大家供大家参考。具体如下:DataView dvCmControlIn
- 首先,确保 IDEA 软件正确安装完成,Java 开发工具包 JDK 安装完成。IDEA 的 Java 项目 (Project) 则相当于
- 简单认识一下Startupnowinandroid项目作为目前google官方来演示MAD(现代Android开发技术)的示例项目,里面大量
- 做Android开发五年了,期间做做停停(去做后台开发,服务器管理),当回来做Android的时候,发现很生疏,好
- MyBatis源码解析_获取SqlSessionFactory我们都知道,在Mybatis中,对数据库的增删改查,实际上是由SqlSessi