【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

相关文章

Java中Map的五种遍历方式实现与对比

《Java中Map的五种遍历方式实现与对比》其实Map遍历藏着多种玩法,有的优雅简洁,有的性能拉满,今天咱们盘一盘这些进阶偏基础的遍历方式,告别重复又臃肿的代码,感兴趣的小伙伴可以了解下... 目录一、先搞懂:Map遍历的核心目标二、几种遍历方式的对比1. 传统EntrySet遍历(最通用)2. Lambd

Spring Boot 中 RestTemplate 的核心用法指南

《SpringBoot中RestTemplate的核心用法指南》本文详细介绍了RestTemplate的使用,包括基础用法、进阶配置技巧、实战案例以及最佳实践建议,通过一个腾讯地图路线规划的案... 目录一、环境准备二、基础用法全解析1. GET 请求的三种姿势2. POST 请求深度实践三、进阶配置技巧1

springboot+redis实现订单过期(超时取消)功能的方法详解

《springboot+redis实现订单过期(超时取消)功能的方法详解》在SpringBoot中使用Redis实现订单过期(超时取消)功能,有多种成熟方案,本文为大家整理了几个详细方法,文中的示例代... 目录一、Redis键过期回调方案(推荐)1. 配置Redis监听器2. 监听键过期事件3. Redi

Spring Boot 处理带文件表单的方式汇总

《SpringBoot处理带文件表单的方式汇总》本文详细介绍了六种处理文件上传的方式,包括@RequestParam、@RequestPart、@ModelAttribute、@ModelAttr... 目录方式 1:@RequestParam接收文件后端代码前端代码特点方式 2:@RequestPart接

SpringBoot整合Zuul全过程

《SpringBoot整合Zuul全过程》Zuul网关是微服务架构中的重要组件,具备统一入口、鉴权校验、动态路由等功能,它通过配置文件进行灵活的路由和过滤器设置,支持Hystrix进行容错处理,还提供... 目录Zuul网关的作用Zuul网关的应用1、网关访问方式2、网关依赖注入3、网关启动器4、网关全局变

SpringBoot全局异常拦截与自定义错误页面实现过程解读

《SpringBoot全局异常拦截与自定义错误页面实现过程解读》本文介绍了SpringBoot中全局异常拦截与自定义错误页面的实现方法,包括异常的分类、SpringBoot默认异常处理机制、全局异常拦... 目录一、引言二、Spring Boot异常处理基础2.1 异常的分类2.2 Spring Boot默

基于SpringBoot实现分布式锁的三种方法

《基于SpringBoot实现分布式锁的三种方法》这篇文章主要为大家详细介绍了基于SpringBoot实现分布式锁的三种方法,文中的示例代码讲解详细,感兴趣的小伙伴可以跟随小编一起学习一下... 目录一、基于Redis原生命令实现分布式锁1. 基础版Redis分布式锁2. 可重入锁实现二、使用Redisso

SpringBoot的全局异常拦截实践过程

《SpringBoot的全局异常拦截实践过程》SpringBoot中使用@ControllerAdvice和@ExceptionHandler实现全局异常拦截,@RestControllerAdvic... 目录@RestControllerAdvice@ResponseStatus(...)@Except

Springboot配置文件相关语法及读取方式详解

《Springboot配置文件相关语法及读取方式详解》本文主要介绍了SpringBoot中的两种配置文件形式,即.properties文件和.yml/.yaml文件,详细讲解了这两种文件的语法和读取方... 目录配置文件的形式语法1、key-value形式2、数组形式读取方式1、通过@value注解2、通过

Java 接口定义变量的示例代码

《Java接口定义变量的示例代码》文章介绍了Java接口中的变量和方法,接口中的变量必须是publicstaticfinal的,用于定义常量,而方法默认是publicabstract的,必须由实现类... 在 Java 中,接口是一种抽象类型,用于定义类必须实现的方法。接口可以包含常量和方法,但不能包含实例