LruCache 源码解析

article/2025/8/25 4:07:19

1. 概述

对于 Android 开发者,LruCache 肯定不陌生,几乎所有的图片缓存框架都会用到它来实现内存缓存等,可见 LruCache 在 Android 开发中的重要性。LRU 是 Least Recently Used 的缩写,近期最少使用的意思。当我们进行缓存的时候,如果缓存满了,会先淘汰使用最少的缓存对象。因为在 Android 中为每个APP分配的内存大小有限,而 LruCache 的使用,可以为缓存指定固定大小的空间,当缓存大小超过这个空间,就会优先淘汰最少使用的缓存对象,从而避免因为缓存对象太大造成的内存溢出。

2. LruCache 的使用

        // 设置LruCache缓存的大小,一般为当前进程可用容量的1/8int cacheSize = (int) (Runtime.getRuntime().totalMemory() / 8);LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>(cacheSize) {@Overrideprotected int sizeOf(String key, Bitmap value) {return value.getRowBytes() * value.getHeight() / 1024;}};lruCache.put("key", bitmap);Bitmap value = lruCache.get("key");

这是 LruCache 基本的用法:指定缓存的大小,当超出指定的大小后会进行回收最小的缓存对象,重写 sizeOf 方法,返回每个存储对象的大小,为何要重写 sizeOf 方法,后面会进行说明。调用 put、get 方法实现从 LruCache 中存储和取出对象。

3. 源码解析

LruCache 是一个泛型类,并没有任何的父类以及实现任何的接口:

public class LruCache<K, V> {......
}

3.1 主要变量

    private final LinkedHashMap<K, V> map;  //LruCache 内部靠 LinkedHashMap实现存储/** Size of this cache in units. Not necessarily the number of elements. */private int size;    //当前缓存的对象大小private int maxSize;    //缓存最大可用空间private int putCount;    // 存储的次数private int createCount;private int evictionCount;    //回收存储对象的次数private int hitCount;private int missCount;

3.2 构造方法

    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);}

在此构造方法中,传入 LruCache 允许存储的最大容量 maxSize,如果传入的 maxSize 小于0,则直接抛出异常。初始化LinkedHashMap 对象,调用的是 LinkedHashMap 三个参数的构造方法,最后一个参数代表 LinkedHashMap 是否进行访问排序。对于 LinkedHashMap 的解析可以看 LinkedHashMap 源码解析。

3.3 put 方法

    public final V put(K key, V value) {if (key == null || value == null) {    //1throw new NullPointerException("key == null || value == null");}V previous;synchronized (this) {putCount++;    //2size += safeSizeOf(key, value);    //3previous = map.put(key, value);    //4if (previous != null) {    //5size -= safeSizeOf(key, previous);}}if (previous != null) {    //6entryRemoved(false, key, previous, value);}trimToSize(maxSize);//7return previous;}

注释1 中,LruCache 是不允许 key 和 value 中任何一个为 null,否则抛出空指针异常。

注释2 中,putCount 的值增加1,记录存储的次数。

注释3 中,size 在原来的基础加上方法 safeSizeOf 返回值,size 存储当前存储的缓存大小。

safeSizeOf :

    private int safeSizeOf(K key, V value) {int result = sizeOf(key, value);if (result < 0) {throw new IllegalStateException("Negative size: " + key + "=" + value);}return result;}

在此方法中核心是调用了方法:sizeOf(key, value)

sizeOf:

    protected int sizeOf(K key, V value) {return 1;}

默认的方法返回值 1,如果每次返回的都是1,而 size 只增加1。如果在初始化 LruCache 对象时候不重写此方法,并返回每个存储对象的大小,构造方法传入的 maxSize 只有用来记录存储的最大个数。如果重写此方法,并返回了每个存储对象的大小,则 maxSize 则表示存储的对象的最大容量。这里 sizeOf 返回值的单位要和构造方法中传入参数的单位一致才有意义,比如大小都字节等。

再回到 put 方法中:

注释 4 ,调用 LinkedHashMap 中的 put 方法,并将返回值赋值给临时变量:V previous;

注释5 ,如果 previous 不为空,则表示已经有此缓存对象,则必须把注释3 中加入的大小再次扣除,将缓存大小恢复到之前。

注释6 ,如果 previous 不为空,则表示已经有此缓存对象,则调用方法 entryRemoved,方法 entryRemoved 为空方法,如果有需要进行重写。

protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) {}

注释7,调用方法 trimToSize,传入的参数为允许存储的最大容量,此方法用于调整缓存大小,来判断缓存是否已满,如果满了就要删除近期最少使用的对象。下面将对方法 trimToSize 进行解释。

最后,put 方法返回的是 previous 对象。

3.4 trimToSize 方法

用 AndroidStudio 追踪源码的方式,LruCache 的 trimToSize 方法如下:

    private void trimToSize(int maxSize) {while (true) {K key;V value;synchronized (this) {if (size < 0 || (map.isEmpty() && size != 0)) {throw new IllegalStateException(getClass().getName()+ ".sizeOf() is reporting inconsistent results!");}if (size <= maxSize) {break;}// BEGIN LAYOUTLIB CHANGE// get the last item in the linked list.// This is not efficient, the goal here is to minimize the changes// compared to the platform version.Map.Entry<K, V> toEvict = null;for (Map.Entry<K, V> entry : map.entrySet()) {    //8toEvict = entry;}// END LAYOUTLIB CHANGEif (toEvict == null) {break;}key = toEvict.getKey();value = toEvict.getValue();map.remove(key);    //9size -= safeSizeOf(key, value);evictionCount++;}entryRemoved(true, key, value, null);}}

在此方法中,是一个 while 的死循环。在此循环中如果当前存储的大小 size 如果比指定的最大缓存大小还小,则跳出死循环。否则继续执行。

注释8 中,取出 LinkedHashMap 中队尾的元素,并赋值给临时变量 Map.Entry<K, V> toEvict。(Android Stuido 方式追踪的源码,这里存在着问题,搞得我怀疑人生)

真正的代码应该如下:

http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/java/android/util/LruCache.java#trimToSize

toEvict 应该为 eldest 方法的返回值:

    public Map.Entry<K, V> eldest() {return head;}

取出的应该是 LinkedHashMap 中链表头部的元素。

注释9 中,调用 remove 方法,用于将 LinkedHashMap 中头部的对象进行移除,并且将存储大小 (size) 的值减去移除的对象的大小。 evictionCount 值加1。

不断的进行死循环,直到最后 size 的值小于 maxSize。

3.5 get 方法

    public final V get(K key) {if (key == null) {    //10throw new NullPointerException("key == null");}V mapValue;synchronized (this) {mapValue = map.get(key);  //11if (mapValue != null) {hitCount++;return mapValue;}missCount++;}/** 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.*/V createdValue = create(key); //12if (createdValue == null) {return null;}synchronized (this) {createCount++;mapValue = map.put(key, createdValue);if (mapValue != null) {// There was a conflict so undo that last putmap.put(key, mapValue);} else {size += safeSizeOf(key, createdValue);}}if (mapValue != null) {entryRemoved(false, key, createdValue, mapValue);return mapValue;} else {trimToSize(maxSize);return createdValue;}}

注释10,如果 key 为空,则抛出空指针异常。

注释11,从 LinkedHashMap 中取出元素,如果不为空则返回。如果 LinkedHashMap 中不存在这个值,则新建一个这样的值,但是新建的方法 create 是空方法,除非进行重写。

    protected V create(K key) {return null;}

 4. 总结

从以上的分析可以得出:

LruCache 底层是一个 LinkedHashMap 作为存储,在初始化 LruCache 对象时候,需要进行指定最大的缓存大小,并重写 sieOf 方法用于计算每次存储的对象大小。如果不重写 sieOf 方法,则初始化时候指定的为可存储的个数。当调用 put 方法存储对象时候,会判断当前缓存的大小是否小于指定的最大缓存,如果当前缓存的不小于指定最大缓存,则会调用 trimToSize 方法进行清理最早访问的对象,即 LinkedHashMap 头部的元素, 直到当前缓存大小小于指定的最大缓存大小。当调用 get 方法时候,则调用的 LinkedHashMap 的 get 方法,LinkedHashMap 会将访问的对象移动到链表的尾部,为 trimToSize 中清理最早访问的对象(链表头部的元素) 做准备。

已经是8号的1点30分,睡了,晚安!

附上 Lrucache 的源码:

http://androidxref.com/9.0.0_r3/xref/frameworks/base/core/java/android/util/LruCache.java#trimToSize

/** Copyright (C) 2011 The Android Open Source Project** Licensed under the Apache License, Version 2.0 (the "License");* you may not use this file except in compliance with the License.* You may obtain a copy of the License at**      http://www.apache.org/licenses/LICENSE-2.0** Unless required by applicable law or agreed to in writing, software* distributed under the License is distributed on an "AS IS" BASIS,* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.* See the License for the specific language governing permissions and* limitations under the License.*/package android.util;import java.util.LinkedHashMap;
import java.util.Map;/*** A cache that holds strong references to a limited number of values. Each time* a value is accessed, it is moved to the head of a queue. When a value is* added to a full cache, the value at the end of that queue is evicted and may* become eligible for garbage collection.** <p>If your cached values hold resources that need to be explicitly released,* override {@link #entryRemoved}.** <p>If a cache miss should be computed on demand for the corresponding keys,* override {@link #create}. This simplifies the calling code, allowing it to* assume a value will always be returned, even when there's a cache miss.** <p>By default, the cache size is measured in the number of entries. Override* {@link #sizeOf} to size the cache in different units. For example, this cache* is limited to 4MiB of bitmaps:* <pre>   {@code*   int cacheSize = 4 * 1024 * 1024; // 4MiB*   LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) {*       protected int sizeOf(String key, Bitmap value) {*           return value.getByteCount();*       }*   }}</pre>** <p>This class is thread-safe. Perform multiple cache operations atomically by* synchronizing on the cache: <pre>   {@code*   synchronized (cache) {*     if (cache.get(key) == null) {*         cache.put(key, value);*     }*   }}</pre>** <p>This class does not allow null to be used as a key or value. A return* value of null from {@link #get}, {@link #put} or {@link #remove} is* unambiguous: the key was not in the cache.** <p>This class appeared in Android 3.1 (Honeycomb MR1); it's available as part* of <a href="http://developer.android.com/sdk/compatibility-library.html">Android's* Support Package</a> for earlier releases.*/
public class LruCache<K, V> {private final LinkedHashMap<K, V> map;/** Size of this cache in units. Not necessarily the number of elements. */private int size;private int maxSize;private int putCount;private int createCount;private int evictionCount;private int hitCount;private int missCount;/*** @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);}/*** Sets the size of the cache.** @param maxSize The new maximum size.*/public void resize(int maxSize) {if (maxSize <= 0) {throw new IllegalArgumentException("maxSize <= 0");}synchronized (this) {this.maxSize = maxSize;}trimToSize(maxSize);}/*** 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) {throw new NullPointerException("key == null");}V mapValue;synchronized (this) {mapValue = map.get(key);if (mapValue != null) {hitCount++;return mapValue;}missCount++;}/** 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.*/V createdValue = create(key);if (createdValue == null) {return null;}synchronized (this) {createCount++;mapValue = map.put(key, createdValue);if (mapValue != null) {// There was a conflict so undo that last putmap.put(key, mapValue);} else {size += safeSizeOf(key, createdValue);}}if (mapValue != null) {entryRemoved(false, key, createdValue, mapValue);return mapValue;} else {trimToSize(maxSize);return createdValue;}}/*** 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++;size += safeSizeOf(key, value);previous = map.put(key, value);if (previous != null) {size -= safeSizeOf(key, previous);}}if (previous != null) {entryRemoved(false, key, previous, value);}trimToSize(maxSize);return previous;}/*** 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) {if (size < 0 || (map.isEmpty() && size != 0)) {throw new IllegalStateException(getClass().getName()+ ".sizeOf() is reporting inconsistent results!");}if (size <= maxSize) {break;}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);}}/*** Removes the entry for {@code key} if it exists.** @return the previous value mapped by {@code key}.*/public final V remove(K key) {if (key == null) {throw new NullPointerException("key == null");}V previous;synchronized (this) {previous = map.remove(key);if (previous != null) {size -= safeSizeOf(key, previous);}}if (previous != null) {entryRemoved(false, key, previous, null);}return previous;}/*** Called for entries that have been evicted or removed. This method is* invoked when a value is evicted to make space, removed by a call to* {@link #remove}, or replaced by a call to {@link #put}. The default* implementation does nothing.** <p>The method is called without synchronization: other threads may* access the cache while this method is executing.** @param evicted true if the entry is being removed to make space, false*     if the removal was caused by a {@link #put} or {@link #remove}.* @param newValue the new value for {@code key}, if it exists. If non-null,*     this removal was caused by a {@link #put}. Otherwise it was caused by*     an eviction or a {@link #remove}.*/protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) {}/*** Called after a cache miss to compute a value for the corresponding key.* Returns the computed value or null if no value can be computed. The* default implementation returns null.** <p>The method is called without synchronization: other threads may* access the cache while this method is executing.** <p>If a value for {@code key} exists in the cache when this method* returns, the created value will be released with {@link #entryRemoved}* and discarded. This can occur when multiple threads request the same key* at the same time (causing multiple values to be created), or when one* thread calls {@link #put} while another is creating a value for the same* key.*/protected V create(K key) {return null;}private int safeSizeOf(K key, V value) {int result = sizeOf(key, value);if (result < 0) {throw new IllegalStateException("Negative size: " + key + "=" + value);}return result;}/*** Returns the size of the entry for {@code key} and {@code value} in* user-defined units.  The default implementation returns 1 so that size* is the number of entries and max size is the maximum number of entries.** <p>An entry's size must not change while it is in the cache.*/protected int sizeOf(K key, V value) {return 1;}/*** Clear the cache, calling {@link #entryRemoved} on each removed entry.*/public final void evictAll() {trimToSize(-1); // -1 will evict 0-sized elements}/*** For caches that do not override {@link #sizeOf}, this returns the number* of entries in the cache. For all other caches, this returns the sum of* the sizes of the entries in this cache.*/public synchronized final int size() {return size;}/*** For caches that do not override {@link #sizeOf}, this returns the maximum* number of entries in the cache. For all other caches, this returns the* maximum sum of the sizes of the entries in this cache.*/public synchronized final int maxSize() {return maxSize;}/*** Returns the number of times {@link #get} returned a value that was* already present in the cache.*/public synchronized final int hitCount() {return hitCount;}/*** Returns the number of times {@link #get} returned null or required a new* value to be created.*/public synchronized final int missCount() {return missCount;}/*** Returns the number of times {@link #create(Object)} returned a value.*/public synchronized final int createCount() {return createCount;}/*** Returns the number of times {@link #put} was called.*/public synchronized final int putCount() {return putCount;}/*** Returns the number of values that have been evicted.*/public synchronized final int evictionCount() {return evictionCount;}/*** Returns a copy of the current contents of the cache, ordered from least* recently accessed to most recently accessed.*/public synchronized final Map<K, V> snapshot() {return new LinkedHashMap<K, V>(map);}@Override public synchronized final String toString() {int accesses = hitCount + missCount;int hitPercent = accesses != 0 ? (100 * hitCount / accesses) : 0;return String.format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]",maxSize, hitCount, missCount, hitPercent);}
}

 


http://chatgpt.dhexx.cn/article/FJMMdC3R.shtml

相关文章

LruCache

LruCache这个类是通过Glide得知的&#xff0c;不过它是自己又基于LRU算法自己写了个LruCache工具类&#xff0c;不过基本原理类似&#xff0c;都是基于LRU算法实现的 1.来源 一般来说&#xff0c;缓存策略主要包含缓存的添加、获取和删除这三类操作。如何添加和获取缓存这个比…

Android基础-LruCache原理解析

一、Android中的缓存策略 一般来说&#xff0c;缓存策略主要包含缓存的添加、获取和删除这三类操作。如何添加和获取缓存这个比较好理解&#xff0c;那么为什么还要删除缓存呢&#xff1f;这是因为不管是内存缓存还是硬盘缓存&#xff0c;它们的缓存大小都是有限的。当缓存满了…

LRUCache详解

1.概念 LRU是Least Recently Used的缩写&#xff0c;意思是最近最少使用&#xff0c;它是一种Cache替换算法。 Cache的容量有限&#xff0c;因此当Cache的容量用完后&#xff0c;而又有新的内容需要添加进来时&#xff0c; 就需要挑选并舍弃原有的部分内容&#xff0c;从而腾出…

LRUCache 详解

LRU算法详解 一、什么是 LRU 算法 就是一种缓存淘汰策略。 计算机的缓存容量有限&#xff0c;如果缓存满了就要删除一些内容&#xff0c;给新内容腾位置。但问题是&#xff0c;删除哪些内容呢&#xff1f;我们肯定希望删掉哪些没什么用的缓存&#xff0c;而把有用的数据继续…

LRU Cache

前言 哈喽&#xff0c;各位小伙伴大家好&#xff0c;本章内容为大家介绍计算机当中为了提高数据相互传输时的效率而引进的一种重要设计结构叫做LRU Cache,下面将为大家详细介绍什么是LRU Cache,以及它是如何是实现的&#xff0c;如何提升效率的。 1.什么是LRU Cache? LRU是L…

uniapp日历原生插件

<template><!-- 打卡日历页面 --><view classall><view class"bar"><!-- 上一个月 --><view class"previous" click"handleCalendar(0)"><button class"barbtn">上一月</button><…

微信小程序使用日历插件

一&#xff0c;添加插件 1&#xff0c;在你的小程序关联的微信公众平台打开 设置》第三方服务》添加插件 2&#xff0c;直接AppID&#xff08;wx92c68dae5a8bb046&#xff09;搜索到该插件并申请授权&#xff0c;授权成功即可在小程序使用 二&#xff0c;小程序使用插件 app…

日历组件

日历组件&#xff1a; <template><div class"calendar" click.stop><div class"input-wrap"><inputtype"text"v-if"dateChangeSets":placeholder"placeholder"class"input dateChangeSets middle…

vue-calendar基于vue的日历插件

本文转载于https://www.cnblogs.com/zwhgithub/p/8005414.html vue-calendar-component 基于 vue 2.0 开发的轻量&#xff0c;高性能日历组件占用内存小&#xff0c;性能好&#xff0c;样式好看&#xff0c;可扩展性强原生 js 开发&#xff0c;没引入第三方库 效果 Install …

实用插件(一)日历插件——My97DatePicker

注&#xff1a;My97DatePicker插件仅限pc端使用&#xff0c;若是app项目&#xff0c;建议使用ICalendar或者Mobiscroll。 &#xff08;ICalendar插件在华为手机上存在兼容性问题&#xff0c;日期不能滚动&#xff0c;但使用很简单&#xff1b;Mobiscroll使用起来较为复杂&…

sys-calendar.js带节假日的日历插件

下载地址 sys-calendar.js带节假日的日历插件&#xff0c;代码引用比较多。 dd:

jquery日历插件,可自定义日期内容

效果图&#xff1a; 使用&#xff1a; <link href"static/css/raoCalendar.css" rel"stylesheet" type"text/css"><script src"static/js/jquery.min.js"></script> <script src"static/js/raoCalendar.js…

两款超好用js日历插件(fullcalendar和zabuto_calendar)

这两款插件特别类似,其实用其中一款即可。 先展示一下我用这两款插件制作的排班系统 这个是fullcalendar插件制作的排班页面,左边新建一系列组和组员,可以将人员直接拖拽至右边的日历上,不同组以颜色区别。 这个是将上面的排班内容用zabuto_calendar插件显示出来,黄色区域…

BootStrap日历插件

BootStrap日历插件 前端引入插件三大步骤 引入插件所需的资源文件 <%--引入BootStrap日历插件相关资源文件--%><%--按照资源文件相互依赖的顺序来引入--%><script type"text/javascript" src"jquery/jquery-1.11.1-min.js"></scrip…

jQuery实现移动端手机选择日期日历插件

效果图 calendar.css html, body {color: #333;margin: 0;height: 100%;font-family: "Microsoft YaHei", "Helvetica Neue", Helvetica, Arial, Verdana, sans-serif;-webkit-font-smoothing: antialiased;-moz-osx-font-smoothing: grayscale;font-weig…

uniapp日历插件

日历插件 效果图一、使用方法二、组件编写&#xff0c;两个文件、直接上代码month.vuecalendar.vue 效果图 一、使用方法 <template><view><view class"" click"open"><text>展示日历{{value[0]}}-{{value[1]}}</text><…

calendar.js多种形式日历插件

下载地址 calendar.js是一款强大的日历插件&#xff0c;有多种形式的日历插件&#xff0c;比如&#xff0c;选择年、选择月、范围等。 dd:

日历插件:bootstrap-datetimepicker

1. 简述 前端插件使用步骤&#xff1a; 1)引入开发包&#xff1a;.js,.css 下载开发包&#xff0c;拷贝到项目webapp目录下 把开发包引入到jsp文件中&#xff1a;<link><script> 2)创建容器&#xff1a;<input type"text"…

最棒的 10 款 jQuery 日历插件

RT&#xff0c; 最棒的 10 款 jQuery 日历插件 做个记号&#xff0c;以后就不用再翻来翻去 1、JavaScript Calendar, JSCal2 地址&#xff1a;点击打开链接 2、Date Picker 地址&#xff1a;点击打开链接 3、 jQuery Frontier Calendar 地址&#xff1a;点击打开链接…

vue日历插件vue-calendar

原始效果&#xff1a; 修改后的效果&#xff1a; 接下来&#xff0c;我们使用它&#xff5e; 1.安装 npm i vue-calendar-component --save cnpm i vue-calendar-component --save //国内镜像 2.在使用到日历插件的文件中引入 import Calendar from vue-calendar-componen…