面试:你懂什么是分布式系统吗?Redis分布式锁都不会?>>>
概念:
LruCache
什么是LruCache?
LruCache实现原理是什么?
这两个问题其实可以作为一个问题来回答,知道了什么是 LruCache,就只然而然的知道 LruCache 的实现原理;Lru的全称是Least Recently Used ,近期最少使用的。所以我们可以推断出 LruCache 的实现原理:把近期最少使用的数据从缓存中移除,保留使用最频繁的数据,那具体代码要怎么实现呢,我们进入到源码中看看。
首先,我们先看一下LinkHashMap
LinkHashMap是继承自HashMap的一个类,对于HashMap来说它只是多定义了两个变量如下,当然也是通过这两个变量以及重写HashMap的部分方法来实现,LRU的功能。
/**
循环链表中一个虚拟的入口,第一个元素是header的next,
最后一个元素是header的尾部
如果map是空的话,那么header.nxt == header && header.prv == header.
nxt,prv,表示一个元素的前后元素,相信学过的链表的道友们都会知道这个的吧
*/
transient LinkedEntry<K, V> header;
/**
* True if access ordered, false if insertion ordered.
这个是用于控制,外部访问链表的时候,是按什么顺序访问的 ,
,true就是按照最近访问来排列元素,从而被遍历,否则就是按照插入顺序来被遍历,当然存储的时候也会根据这个变量来做特殊的处理,
true的时候那么就会在访问和删除的时候修改链表的元素的before和next的指针。
*/
private final boolean accessOrder;
LinkedHashMap的关键构造方法之一
/**
* @param initialCapacity 定义LinkedHashMap的初始容量
* the initial capacity of this hash map.
* @param loadFactor 定义加载因子,用于当容量不够用的时候,扩展容量时,
是用初始容量*加载因子等于之后扩展的容量。
* the initial load factor.
* @param accessOrder
* {@code true} if the ordering should be done based on the last
* access (from least-recently accessed to most-recently
* accessed), and {@code false} if the ordering should be the
* order in which the entries were inserted.
* @throws IllegalArgumentException
* when the capacity is less than zero or the load factor is
* less or equal to zero.
*/
public LinkedHashMap(
int initialCapacity, float loadFactor, boolean accessOrder) {
super(initialCapacity, loadFactor);
init();
this.accessOrder = accessOrder;
}
可以看到LinkedHashMap的构造方法就是调用了父类构造方法,然后给accessOrder
赋值,其中调用了init(),那接下来我们一起来看看init(),init很简单就是给header赋值了,指向了一个LinkedEntry对象。
@Override void addNewEntry(K key, V value, int hash, int index) {
LinkedEntry<K, V> header = this.header;
// Remove eldest entry if instructed to do so.
LinkedEntry<K, V> eldest = header.nxt;
if (eldest != header && removeEldestEntry(eldest)) {
remove(eldest.key);
}
// Create new entry, link it on to list, and put it into table
LinkedEntry<K, V> oldTail = header.prv;
LinkedEntry<K, V> newTail = new LinkedEntry<K,V>(
key, value, hash, table[index], header, oldTail);
table[index] = oldTail.nxt = header.prv = newTail;
}
从addNewEntry代码可以看到 ,首先保存了当前链表的头部,然后判断是否需要移除最不常访问的entry,再将它移除,因为LinkedHashMap是始终将最不常访问的放在头部,所以header.nxt便是就老的entry。 然后创建一个新的entry,记录下当前最近被访问的元素即尾部元素,由于是循环链表所以头部的prv,便是当前最近被访问的元素,然后新插入的元素应该位于尾部,我们假设插入的元素为a, 那么a的prv,便是刚刚记录下来的最近被访问的元素,而nxt这是header元素,从而将entry的nxt,pre调整好之后,插入功能这也就完成了。而这个方法是在HashMap的put方法中调用的,LinkedHashMap重写了HashMap的addNewEntry方法。从而完成链表操作。
接下来我们来看看,查询操作get,LinkedHashMap重写了HashMap的get方法,具体代码如下:
@Override public V get(Object key) {
/*
* This method is overridden to eliminate the need for a polymorphic
* invocation in superclass at the expense of code duplication.
*/
if (key == null) {
HashMapEntry<K, V> e = entryForNullKey;
if (e == null)
return null;
if (accessOrder)
makeTail((LinkedEntry<K, V>) e);
return e.value;
}
int hash = Collections.secondaryHash(key);
HashMapEntry<K, V>[] tab = table;
for (HashMapEntry<K, V> e = tab[hash & (tab.length - 1)];
e != null; e = e.next) {
K eKey = e.key;
if (eKey == key || (e.hash == hash && key.equals(eKey))) {
if (accessOrder)
makeTail((LinkedEntry<K, V>) e);
return e.value;
}
}
return null;
}
https://www.jianshu.com/p/b0442c719525
LruCache源码分析
public class LruCache<K, V> {
//缓存 map 集合,为什么要用LinkedHashMap
//因为没错取了缓存值之后,都要进行排序,以确保
//下次移除的是最少使用的值
private final LinkedHashMap<K, V> map;
//当前缓存的值
private int size;
//最大值
private int maxSize;
//添加到缓存中的个数
private int putCount;
//创建的个数
private int createCount;
//被移除的个数
private int evictionCount;
//命中个数
private int hitCount;
//丢失个数
private int missCount;
//实例化 Lru,需要传入缓存的最大值
//这个最大值可以是个数,比如对象的个数,也可以是内存的大小
//比如,最大内存只能缓存5兆
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);
}
//重置最大缓存的值
public void resize(int maxSize) {
if (maxSize <= 0) {
throw new IllegalArgumentException("maxSize <= 0");
}
synchronized (this) {
this.maxSize = maxSize;
}
trimToSize(maxSize);
}
//通过 key 获取缓存值
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++;
}
//如果没有,用户可以去创建
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 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;
}
}
//添加缓存,跟上面这个方法的 create 之后的代码一样的
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;
}
//检测缓存是否越界
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 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;
}
//这里用户可以重写它,实现数据和内存回收操作
protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) {}
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;
}
//这个方法要特别注意,跟我们实例化 LruCache 的 maxSize 要呼应,怎么做到呼应呢,比如 maxSize 的大小为缓存的个数,这里就是 return 1就 ok,如果是内存的大小,如果5M,这个就不能是个数 了,这是应该是每个缓存 value 的 size 大小,如果是 Bitmap,这应该是 bitmap.getByteCount();
protected int sizeOf(K key, V value) {
return 1;
}
//清空缓存
public final void evictAll() {
trimToSize(-1); // -1 will evict 0-sized elements
}
public synchronized final int size() {
return size;
}
public synchronized final int maxSize() {
return maxSize;
}
public synchronized final int hitCount() {
return hitCount;
}
public synchronized final int missCount() {
return missCount;
}
public synchronized final int createCount() {
return createCount;
}
public synchronized final int putCount() {
return putCount;
}
public synchronized final int evictionCount() {
return evictionCount;
}
public synchronized final Map<K, V> snapshot() {
return new LinkedHashMap<K, V>(map);
}
}
}