【Java源码分析】Android-LruCache源码分析

2024-02-11 08:32

本文主要是介绍【Java源码分析】Android-LruCache源码分析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

内部实现是LinkedHashMap,保持有限数量的值得强引用,值被访问之后就被移动到队列的首部。当队列满了之后,尾部的值会被移除以便于GC回收

类的定义

public class LruCache<K, V> {}
  1. 如果被缓存的值所拥有的职员需要被显式的释放,重载entryRemoved()方法
  2. 默认情况下size方法返回的是条目数,如果需要返回缓存大小,可以重载sizeOf()
  3. 线程安全的类
  4. 不允许NULL的key,因此get put remove返回null的时候是没有二义性的

构造方法

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,如果没有重载sizeOf()那么maxSize是最大条目数,如果重载了,就是用于重载所用单位

取值方法

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

如果对应的key存在于缓存或者可以被创建,那么返回key对应的value。否则返回null.
如果在创建过程中出现了值得冲突,那么就丢弃当前创建的value,保留之前的。

存值方法

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

将当前的键值对存入Map,并把当前键值对移到队列最前方,返回该key之前映射的值

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

键值对被移除时调用,默认是空实现。方法是没有实现同步的,所以在执行时可能被其他线程访问。如果第一个参数是true,就代表是移除以空出空间。如果是false代表是被put或者remove调用。最后一个参数是key对应的新值,如果非空,就说明是被put调用,如果为空,说明是被eviction或者remove

移除最久的键值对

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

移除存在最久的键值对,保证缓存容量在指定容量之内,参数就是缓存阈值。

删除操作

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

删除key所映射的之前的值,返回值是key先前的映射值

缓存未命中时计算给定key的相关值时被调用的方法,在get中被使用(当get的时候当前key没有对应的键值对,就需要调用create()创建)这个方法需要和get结合来看

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;
}protected int sizeOf(K key, V value) {return 1;
}

返回给定参数键值对应实体的大小,该大小是用户定义的单位大小比如个数或者KB。默认返回1代表个数

清空缓存

public final void evictAll() {trimToSize(-1); // -1 will evict 0-sized elements
}

对每一个entry调用entryRemoved

获取缓存大小

public synchronized final int size() {return size;
}

对于没有覆写sizeOf()的时候返回的是缓存中实体的最大个数,如果覆写了sizeOf()返回的是所有实体大小之和的最大值

缓存命中数

public synchronized final int hitCount() {return hitCount;
}public synchronized final int missCount() {return missCount;
}

get方法命中次数和未命中数

返回快照

//  ordered from least recently accessed to most recently accessed.
public synchronized final Map<K, V> snapshot() {return new LinkedHashMap<K, V>(map);
}

返回当前缓存的一个副本

这篇关于【Java源码分析】Android-LruCache源码分析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/699340

相关文章

Spring Cloud Hystrix原理与注意事项小结

《SpringCloudHystrix原理与注意事项小结》本文介绍了Hystrix的基本概念、工作原理以及其在实际开发中的应用方式,通过对Hystrix的深入学习,开发者可以在分布式系统中实现精细... 目录一、Spring Cloud Hystrix概述和设计目标(一)Spring Cloud Hystr

Go使用pprof进行CPU,内存和阻塞情况分析

《Go使用pprof进行CPU,内存和阻塞情况分析》Go语言提供了强大的pprof工具,用于分析CPU、内存、Goroutine阻塞等性能问题,帮助开发者优化程序,提高运行效率,下面我们就来深入了解下... 目录1. pprof 介绍2. 快速上手:启用 pprof3. CPU Profiling:分析 C

Spring Boot整合消息队列RabbitMQ的实现示例

《SpringBoot整合消息队列RabbitMQ的实现示例》本文主要介绍了SpringBoot整合消息队列RabbitMQ的实现示例,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的... 目录RabbitMQ 简介与安装1. RabbitMQ 简介2. RabbitMQ 安装Spring

springMVC返回Http响应的实现

《springMVC返回Http响应的实现》本文主要介绍了在SpringBoot中使用@Controller、@ResponseBody和@RestController注解进行HTTP响应返回的方法,... 目录一、返回页面二、@Controller和@ResponseBody与RestController

JAVA集成本地部署的DeepSeek的图文教程

《JAVA集成本地部署的DeepSeek的图文教程》本文主要介绍了JAVA集成本地部署的DeepSeek的图文教程,包含配置环境变量及下载DeepSeek-R1模型并启动,具有一定的参考价值,感兴趣的... 目录一、下载部署DeepSeek1.下载ollama2.下载DeepSeek-R1模型并启动 二、J

springboot rocketmq配置生产者和消息者的步骤

《springbootrocketmq配置生产者和消息者的步骤》本文介绍了如何在SpringBoot中集成RocketMQ,包括添加依赖、配置application.yml、创建生产者和消费者,并展... 目录1. 添加依赖2. 配置application.yml3. 创建生产者4. 创建消费者5. 使用在

Spring Retry 实现乐观锁重试实践记录

《SpringRetry实现乐观锁重试实践记录》本文介绍了在秒杀商品SKU表中使用乐观锁和MybatisPlus配置乐观锁的方法,并分析了测试环境和生产环境的隔离级别对乐观锁的影响,通过简单验证,... 目录一、场景分析 二、简单验证 2.1、可重复读 2.2、读已提交 三、最佳实践 3.1、配置重试模板

Spring中@Lazy注解的使用技巧与实例解析

《Spring中@Lazy注解的使用技巧与实例解析》@Lazy注解在Spring框架中用于延迟Bean的初始化,优化应用启动性能,它不仅适用于@Bean和@Component,还可以用于注入点,通过将... 目录一、@Lazy注解的作用(一)延迟Bean的初始化(二)与@Autowired结合使用二、实例解

SpringBoot使用Jasypt对YML文件配置内容加密的方法(数据库密码加密)

《SpringBoot使用Jasypt对YML文件配置内容加密的方法(数据库密码加密)》本文介绍了如何在SpringBoot项目中使用Jasypt对application.yml文件中的敏感信息(如数... 目录SpringBoot使用Jasypt对YML文件配置内容进行加密(例:数据库密码加密)前言一、J

Java中有什么工具可以进行代码反编译详解

《Java中有什么工具可以进行代码反编译详解》:本文主要介绍Java中有什么工具可以进行代码反编译的相关资,料,包括JD-GUI、CFR、Procyon、Fernflower、Javap、Byte... 目录1.JD-GUI2.CFR3.Procyon Decompiler4.Fernflower5.Jav