【源代码】LruCache源代码剖析
上一篇分析了LinkedHashMap源代码,这个Map集合除了拥有HashMap的大部分特性之外。还拥有链表的特点,即能够保持遍历顺序与插入顺序一致。
另外。当我们将accessOrder设置为true时。能够使遍历顺序和訪问顺序一致,其内部双向链表将会依照最近最少訪问到最近最多訪问的顺序排列Entry对象,这能够用来做缓存。
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;//put次数
private int createCount;//create次数
private int evictionCount;//回收次数
private int hitCount;//命中次数
private int missCount;//丢失次数
LinkedHashMap的初始化放在构造器中:
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);
}
首先是put方法:
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) {//之前已经插入过同样的key
size -= safeSizeOf(key, previous);//那么减去该entry的容量,由于发生覆盖
}
}
if (previous != null) {
entryRemoved(false, key, previous, value);//这种方法默认空实现
}
trimToSize(maxSize);//若容量超过maxsize,将会删除近期非常少訪问的entry
return previous;
}
除此之外,put操作被加锁了,所以是线程安全的!
public void trimToSize(int maxSize) {
while (true) {//不断删除linkedHashMap头部entry,也就是近期最少訪问的条目。直到size小于最大容量
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 || map.isEmpty()) {//直到容量小于最大容量为止
break;
}
Map.Entry<K, V> toEvict = map.entrySet().iterator().next();//指向链表头
key = toEvict.getKey();
value = toEvict.getValue();
map.remove(key);//删除最少訪问的entry
size -= safeSizeOf(key, value);
evictionCount++;
}
entryRemoved(true, key, value, null);
}
}
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;
}
Map.Entry<K, V> toEvict = null;
for (Map.Entry<K, V> entry : map.entrySet()) {
toEvict = entry;
}
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 get(K key) {
if (key == null) {//不同意空键
throw new NullPointerException("key == null");
}
V mapValue;
synchronized (this) {//线程安全
mapValue = map.get(key);//调用LinkedHashMap的get方法
if (mapValue != null) {
hitCount++;//命中次数加1
return mapValue;//返回value
}
missCount++;//未命中
}
V createdValue = create(key);//默认返回为false
if (createdValue == null) {
return null;
}
synchronized (this) {
createCount++;//假设创建成功,那么create次数加1
mapValue = map.put(key, createdValue);//放到哈希表中
if (mapValue != null) {
// There was a conflict so undo that last put
map.put(key, mapValue);
} else {
size += safeSizeOf(key, createdValue);
}
}
if (mapValue != null) {
entryRemoved(false, key, createdValue, mapValue);
return mapValue;
} else {
trimToSize(maxSize);
return createdValue;
}
}
public final V remove(K key) {
if (key == null) {
throw new NullPointerException("key == null");
}
V previous;
synchronized (this) {
previous = map.remove(key);//调用LinkedHashMap的remove方法
if (previous != null) {
size -= safeSizeOf(key, previous);
}
}
if (previous != null) {
entryRemoved(false, key, previous, null);
}
return previous;//返回value
}
sizeof:这种方法用于计算每一个条目的大小,子类必须得复写这个类。
protected int sizeOf(K key, V value) {//用于计算每一个条目的大小
return 1;
}
snapshot方法,返回当前缓存中全部的条目集合
public synchronized final Map<K, V> snapshot() {
return new LinkedHashMap<K, V>(map);
}
【源代码】LruCache源代码剖析的更多相关文章
- android之LruCache源代码解析
移动设备开发中,因为移动设备(手机等)的内存有限,所以使用有效的缓存技术是必要的.android提供来一个缓存工具类LruCache,开发中我们会经经常使用到,以下来他是怎样实现的. 在package ...
- 图像库---Image Datasets---OpenSift源代码---openSurf源代码
1.Computer Vision Datasets on the web http://www.cvpapers.com/datasets.html 2.Dataset Reference http ...
- MINA2 源代码学习--源代码结构梳理
一.mina总体框架与案例: 1.总体结构图: 简述:以上是一张来自网上比較经典的图,总体上揭示了mina的结构,当中IoService包括clientIoConnector和服务端IoAccepto ...
- 【Java集合源代码剖析】TreeMap源代码剖析
转载请注明出处:http://blog.csdn.net/ns_code/article/details/36421085 前言 本文不打算延续前几篇的风格(对全部的源代码加入凝视),由于要理解透Tr ...
- Java To CSharp源代码转换
前言 开发环境 客户端:Unity3D开发(C#) 服务器:Java (基于Java7) 日 期:2016年09月 需求说明 部分服务器的部分逻辑功能在客户端实现一遍,可以简单的理解为服务器的部分 ...
- Apple II DOS 源代码发布
加州山景城的计算机历史博物馆不仅仅展示硬件,还展示软件.博物馆此前已发布了著名软件MacPaint .Photoshop和APL的源代码,现在它公开了1978年的Apple II DOS源代码.源代码 ...
- 在Android中调用C#写的WebService(附源代码)
由于项目中要使用Android调用C#写的WebService,于是便有了这篇文章.在学习的过程中,发现在C#中直接调用WebService方便得多,直接添加一个引用,便可以直接使用将WebServi ...
- 1、android源代码下载与跟踪
学习Android源代码的目的 理解Android API查找API(Activity.Content Provider等) 高级应用开发(ROM定制) 在不同平台下载Android源代码 W ...
- Ubuntu10.04下载并编译Android4.3源代码
注:转载或引用请标明出处 http://blog.csdn.net/luzhenrong45/article/details/9719433 去年用Ubuntu10.10成功下载并编译Andro ...
随机推荐
- Java的9种基本数据类型以及封装类
Java的9种基本数据类型以及封装类 基本类型 大小(单位/字节) 默认值 封装类 byte 1 (byte)0 Byte short 2 (short)0 Short int 4 0 Integer ...
- PAT Basic 1034
1034 有理数四则运算 本题要求编写程序,计算2个有理数的和.差.积.商. 输入格式: 输入在一行中按照“a1/b1 a2/b2”的格式给出两个分数形式的有理数,其中分子和分母全是整型范围内的整数, ...
- python基础学习笔记——模块
自定义模块 我们今天来学习一下自定义模块(也就是私人订制),我们要自定义模块,首先就要知道什么是模块啊 一个函数封装一个功能,比如现在有一个软件,不可能将所有程序都写入一个文件,所以咱们应该分文件,组 ...
- IE浏览器部分js代码不生效的问题
[小小坑记录] 问题描述:IE浏览器写好功能代码之后,在调试模式下程序能正常运行.不开启调试模式正常访问时js部分功能代码不生效. 原因:在测试时用了console对象在控制台输出一一些内容,而IE的 ...
- 【LeetCode】Integer to Roman(整数转罗马数字)
这道题是LeetCode里的第12道题. 吐了,刚做完"罗马数字转整数",现在又做这个.这个没什么想法,只能想到使用if语句嵌套,或者使用哈希表.但哈希表我还不熟练啊.先拿if嵌套 ...
- nginx的详解(四)
10.nginx的访问控制及DDOS预防1)访问控制配置基于各种原因,Ningx有时要进行访问控制.比如说,一般网站的后台都不能让外部访问,所以要添加 IP 限制,通常只允许公司的IP访问.访问控制就 ...
- P1136 迎接仪式 (动态规划)
题目描述 LHX教主要来X市指导OI学习工作了.为了迎接教主,在一条道路旁,一群Orz教主er穿着文化衫站在道路两旁迎接教主,每件文化衫上都印着大字.一旁的Orzer依次摆出“欢迎欢迎欢迎欢迎……”的 ...
- POJ 3585 Accumulation Degree
二次扫描与换根法 用于解决无根树,对于每一个节点作为根时都要统计 做法: 1.先以任意一个节点为根,做树形DP,保存每个节点的DP值 2.然后自上而下dfs,对于每个节点考虑以他为根的最大值 #inc ...
- Day 3 网络基础
网络基础 一.什么是互联网协议及为何要有互联网协议 ? 互联网协议:指的就是一系列统一的标准,这些标准称之为互联网协议.互联网的本质就是一系列的协议,总称为‘互联网协议’(Internet Proto ...
- BZOJ——1607: [Usaco2008 Dec]Patting Heads 轻拍牛头
http://www.lydsy.com/JudgeOnline/problem.php?id=1607 Time Limit: 3 Sec Memory Limit: 64 MBSubmit: 2 ...