Java和Android的LRU缓存及实现原理
一、概述
Android提供了LRUCache类,可以方便的使用它来实现LRU算法的缓存。Java提供了LinkedHashMap,可以用该类很方便的实现LRU算法,Java的LRULinkedHashMap就是直接继承了LinkedHashMap,进行了极少的改动后就可以实现LRU算法。
二、Java的LRU算法
Java的LRU算法的基础是LinkedHashMap,LinkedHashMap继承了HashMap,并且在HashMap的基础上进行了一定的改动,以实现LRU算法。
1、HashMap
首先需要说明的是,HashMap将每一个节点信息存储在Entry<K,V>结构中。Entry<K,V>中存储了节点对应的key、value、hash信息,同时存储了当前节点的下一个节点的引用。因此Entry<K,V>是一个单向链表。HashMap的存储结构是一个数组加单向链表的形式。每一个key对应的hashCode,在HashMap的数组中都可以找到一个位置;而如果多个key对应了相同的hashCode,那么他们在数组中对应在相同的位置上,这时,HashMap将把对应的信息放到Entry<K,V>中,并使用链表连接这些Entry<K,V>。
staticclassEntry<K,V>implementsMap.Entry<K,V>{
finalKkey;
Vvalue;
Entry<K,V>next;
inthash;
/**
*Createsnewentry.
*/
Entry(inth,Kk,Vv,Entry<K,V>n){
value=v;
next=n;
key=k;
hash=h;
}
publicfinalKgetKey(){
returnkey;
}
publicfinalVgetValue(){
returnvalue;
}
publicfinalVsetValue(VnewValue){
VoldValue=value;
value=newValue;
returnoldValue;
}
publicfinalbooleanequals(Objecto){
if(!(oinstanceofMap.Entry))
returnfalse;
Map.Entrye=(Map.Entry)o;
Objectk1=getKey();
Objectk2=e.getKey();
if(k1==k2||(k1!=null&&k1.equals(k2))){
Objectv1=getValue();
Objectv2=e.getValue();
if(v1==v2||(v1!=null&&v1.equals(v2)))
returntrue;
}
returnfalse;
}
publicfinalinthashCode(){
returnObjects.hashCode(getKey())^Objects.hashCode(getValue());
}
publicfinalStringtoString(){
returngetKey()+"="+getValue();
}
/**
*Thismethodisinvokedwheneverthevalueinanentryis
*overwrittenbyaninvocationofput(k,v)forakeykthat'salready
*intheHashMap.
*/
voidrecordAccess(HashMap<K,V>m){
}
/**
*Thismethodisinvokedwhenevertheentryis
*removedfromthetable.
*/
voidrecordRemoval(HashMap<K,V>m){
}
}
下面贴一下HashMap的put方法的代码,并进行分析
publicVput(Kkey,Vvalue){
if(table==EMPTY_TABLE){
inflateTable(threshold);
}
if(key==null)
returnputForNullKey(value);
//以上信息不关心,下面是正常的插入逻辑。
//首先计算hashCode
inthash=hash(key);
//通过计算得到的hashCode,计算出hashCode在数组中的位置
inti=indexFor(hash,table.length);
//for循环,找到在HashMap中是否存在一个节点,对应的key与传入的key完全一致。如果存在,说明用户想要替换该key对应的value值,因此直接替换value即可返回。
for(Entry<K,V>e=table[i];e!=null;e=e.next){
Objectk;
if(e.hash==hash&&((k=e.key)==key||key.equals(k))){
VoldValue=e.value;
e.value=value;
e.recordAccess(this);
returnoldValue;
}
}
//逻辑执行到此处,说明HashMap中不存在完全一致的kye.调用addEntry,新建一个节点保存key、value信息,并增加到HashMap中
modCount++;
addEntry(hash,key,value,i);
returnnull;
}
在上面的代码中增加了一些注释,可以对整体有一个了解。下面具体对一些值得分析的点进行说明。
<1>inti=indexFor(hash,table.length);
可以看一下源码:
staticintindexFor(inth,intlength){
//assertInteger.bitCount(length)==1:"lengthmustbeanon-zeropowerof2";
returnh&(length-1);
}
为什么获得的hashCode(h)要和(length-1)进行按位与运算?这是为了保证去除掉h的高位信息。如果数组大小为8(1000),而计算出的h的值为10(1010),如果直接获取数组的index为10的数据,肯定会抛出数组超出界限异常。所以使用按位与(0111&1010),成功清除掉高位信息,得到2(0010),表示对应数组中index为2的数据。效果与取余相同,但是位运算的效率明显更高。
但是这样有一个问题,如果length为9,获取得length-1信息为8(1000),这样进行位运算,不但不能清除高位数据,得到的结果肯定不对。所以数组的大小一定有什么特别的地方。通过查看源码,可以发现,HashMap无时无刻不在保证对应的数组个数为2的n次方。
首先在put的时候,调用inflateTable方法。重点在于roundUpToPowerOf2方法,虽然它的内容包含大量的位相关的运算和处理,没有看的很明白,但是注释已经明确了,会保证数组的个数为2的n次方。
privatevoidinflateTable(inttoSize){
//Findapowerof2>=toSize
intcapacity=roundUpToPowerOf2(toSize);
threshold=(int)Math.min(capacity*loadFactor,MAXIMUM_CAPACITY+1);
table=newEntry[capacity];
initHashSeedAsNeeded(capacity);
}
其次,在addEntry等其他位置,也会使用(2*table.length)、table.length<<1等方式,保证数组的个数为2的n次方。
<2>for(Entry<K,V>e=table[i];e!=null;e=e.next)
因为HashMap使用的是数组加链表的形式,所以通过hashCode获取到在数组中的位置后,得到的不是一个Entry<K,V>,而是一个Entry<K,V>的链表,一定要循环链表,获取key对应的value。
<3>addEntry(hash,key,value,i);
先判断数组个数是否超出阈值,如果超过,需要增加数组个数。然后会新建一个Entry,并加到数组中。
/**
*Addsanewentrywiththespecifiedkey,valueandhashcodeto
*thespecifiedbucket.Itistheresponsibilityofthis
*methodtoresizethetableifappropriate.
*
*Subclassoverridesthistoalterthebehaviorofputmethod.
*/
voidaddEntry(inthash,Kkey,Vvalue,intbucketIndex){
if((size>=threshold)&&(null!=table[bucketIndex])){
resize(2*table.length);
hash=(null!=key)?hash(key):0;
bucketIndex=indexFor(hash,table.length);
}
createEntry(hash,key,value,bucketIndex);
}
/**
*LikeaddEntryexceptthatthisversionisusedwhencreatingentries
*aspartofMapconstructionor"pseudo-construction"(cloning,
*deserialization).Thisversionneedn'tworryaboutresizingthetable.
*
*SubclassoverridesthistoalterthebehaviorofHashMap(Map),
*clone,andreadObject.
*/
voidcreateEntry(inthash,Kkey,Vvalue,intbucketIndex){
Entry<K,V>e=table[bucketIndex];
table[bucketIndex]=newEntry<>(hash,key,value,e);
size++;
}
2、LinkedHashMap
LinkedHashMap在HashMap的基础上,进行了修改。首先将Entry由单向链表改成双向链表。增加了before和after两个队Entry的引用。
privatestaticclassEntry<K,V>extendsHashMap.Entry<K,V>{
//Thesefieldscomprisethedoublylinkedlistusedforiteration.
Entry<K,V>before,after;
Entry(inthash,Kkey,Vvalue,HashMap.Entry<K,V>next){
super(hash,key,value,next);
}
/**
*Removesthisentryfromthelinkedlist.
*/
privatevoidremove(){
before.after=after;
after.before=before;
}
/**
*Insertsthisentrybeforethespecifiedexistingentryinthelist.
*/
privatevoidaddBefore(Entry<K,V>existingEntry){
after=existingEntry;
before=existingEntry.before;
before.after=this;
after.before=this;
}
/**
*Thismethodisinvokedbythesuperclasswheneverthevalue
*ofapre-existingentryisreadbyMap.getormodifiedbyMap.set.
*IftheenclosingMapisaccess-ordered,itmovestheentry
*totheendofthelist;otherwise,itdoesnothing.
*/
voidrecordAccess(HashMap<K,V>m){
LinkedHashMap<K,V>lm=(LinkedHashMap<K,V>)m;
if(lm.accessOrder){
lm.modCount++;
remove();
addBefore(lm.header);
}
}
voidrecordRemoval(HashMap<K,V>m){
remove();
}
}
同时,LinkedHashMap提供了一个对Entry的引用header(privatetransientEntry<K,V>header)。header的作用就是永远只是HashMap中所有成员的头(header.after)和尾(header.before)。这样把HashMap本身的数组加链表的格式进行了修改。在LinkedHashMap中,即保留了HashMap的数组加链表的数据保存格式,同时增加了一套header作为开始标记的双向链表(我们暂且称之为header的双向链表)。LinkedHashMap就是通过header的双向链表来实现LRU算法的。header.after永远指向最近最不常使用的那个节点,删除的话,就是删除这个header.after对应的节点。相对的,header.before指向的就是刚刚使用过的那个节点。
LinkedHashMap并没有提供put方法,但是LinkedHashMap重写了addEntry和createEntry方法,如下:
/**
*Thisoverridealtersbehaviorofsuperclassputmethod.Itcausesnewly
*allocatedentrytogetinsertedattheendofthelinkedlistand
*removestheeldestentryifappropriate.
*/
voidaddEntry(inthash,Kkey,Vvalue,intbucketIndex){
super.addEntry(hash,key,value,bucketIndex);
//Removeeldestentryifinstructed
Entry<K,V>eldest=header.after;
if(removeEldestEntry(eldest)){
removeEntryForKey(eldest.key);
}
}
/**
*ThisoverridediffersfromaddEntryinthatitdoesn'tresizethe
*tableorremovetheeldestentry.
*/
voidcreateEntry(inthash,Kkey,Vvalue,intbucketIndex){
HashMap.Entry<K,V>old=table[bucketIndex];
Entry<K,V>e=newEntry<>(hash,key,value,old);
table[bucketIndex]=e;
e.addBefore(header);
size++;
}
HashMap的put方法,调用了addEntry方法;HashMap的addEntry方法又调用了createEntry方法。因此可以把上面的两个方法和HashMap中的内容放到一起,方便分析,形成如下方法:
voidaddEntry(inthash,Kkey,Vvalue,intbucketIndex){
if((size>=threshold)&&(null!=table[bucketIndex])){
resize(2*table.length);
hash=(null!=key)?hash(key):0;
bucketIndex=indexFor(hash,table.length);
}
HashMap.Entry<K,V>old=table[bucketIndex];
Entry<K,V>e=newEntry<>(hash,key,value,old);
table[bucketIndex]=e;
e.addBefore(header);
size++;
//Removeeldestentryifinstructed
Entry<K,V>eldest=header.after;
if(removeEldestEntry(eldest)){
removeEntryForKey(eldest.key);
}
}
同样,先判断是否超出阈值,超出则增加数组的个数。然后创建Entry对象,并加入到HashMap对应的数组和链表中。与HashMap不同的是LinkedHashMap增加了e.addBefore(header);和removeEntryForKey(eldest.key);这样两个操作。
首先分析一下e.addBefore(header)。其中e是LinkedHashMap.Entry对象,addBefore代码如下,作用就是讲header与当前对象相关联,使当前对象增加到header的双向链表的尾部(header.before):
privatevoidaddBefore(Entry<K,V>existingEntry){
after=existingEntry;
before=existingEntry.before;
before.after=this;
after.before=this;
}
其次是另一个重点,代码如下:
//Removeeldestentryifinstructed
Entry<K,V>eldest=header.after;
if(removeEldestEntry(eldest)){
removeEntryForKey(eldest.key);
}
其中,removeEldestEntry判断是否需要删除最近最不常使用的那个节点。LinkedHashMap中的removeEldestEntry(eldest)方法永远返回false,如果我们要实现LRU算法,就需要重写这个方法,判断在什么情况下,删除最近最不常使用的节点。removeEntryForKey的作用就是将key对应的节点在HashMap的数组加链表结构中删除,源码如下:
finalEntry<K,V>removeEntryForKey(Objectkey){
if(size==0){
returnnull;
}
inthash=(key==null)?0:hash(key);
inti=indexFor(hash,table.length);
Entry<K,V>prev=table[i];
Entry<K,V>e=prev;
while(e!=null){
Entry<K,V>next=e.next;
Objectk;
if(e.hash==hash&&
((k=e.key)==key||(key!=null&&key.equals(k)))){
modCount++;
size--;
if(prev==e)
table[i]=next;
else
prev.next=next;
e.recordRemoval(this);
returne;
}
prev=e;
e=next;
}
returne;
}
removeEntryForKey是HashMap的方法,对LinkedHashMap中header的双向链表无能为力,而LinkedHashMap又没有重写这个方法,那header的双向链表要如何处理呢。
仔细看一下代码,可以看到在成功删除了HashMap中的节点后,调用了e.recordRemoval(this);方法。这个方法在HashMap中为空,LinkedHashMap的Entry则实现了这个方法。其中remove()方法中的两行代码为双向链表中删除当前节点的标准代码,不解释。
/**
*Removesthisentryfromthelinkedlist.
*/
privatevoidremove(){
before.after=after;
after.before=before;
}voidrecordRemoval(HashMap<K,V>m){
remove();
}
以上,LinkedHashMap增加节点的代码分析完毕,可以看到完美的将新增的节点放在了header双向链表的末尾。
但是,这样显然是先进先出的算法,而不是最近最不常使用算法。需要在get的时候,更新header双向链表,把刚刚get的节点放到header双向链表的末尾。我们来看看get的源码:
publicVget(Objectkey){
Entry<K,V>e=(Entry<K,V>)getEntry(key);
if(e==null)
returnnull;
e.recordAccess(this);
returne.value;
}
代码很短,第一行的getEntry调用的是HashMap的getEntry方法,不需要解释。真正处理header双向链表的代码是e.recordAccess(this)。看一下代码:
/**
*Removesthisentryfromthelinkedlist.
*/
privatevoidremove(){
before.after=after;
after.before=before;
}
/**
*Insertsthisentrybeforethespecifiedexistingentryinthelist.
*/
privatevoidaddBefore(Entry<K,V>existingEntry){
after=existingEntry;
before=existingEntry.before;
before.after=this;
after.before=this;
}
/**
*Thismethodisinvokedbythesuperclasswheneverthevalue
*ofapre-existingentryisreadbyMap.getormodifiedbyMap.set.
*IftheenclosingMapisaccess-ordered,itmovestheentry
*totheendofthelist;otherwise,itdoesnothing.
*/
voidrecordAccess(HashMap<K,V>m){
LinkedHashMap<K,V>lm=(LinkedHashMap<K,V>)m;
if(lm.accessOrder){
lm.modCount++;
remove();
addBefore(lm.header);
}
}
首先在header双向链表中删除当前节点,再将当前节点添加到header双向链表的末尾。当然,在调用LinkedHashMap的时候,需要将accessOrder设置为true,否则就是FIFO算法。
三、Android的LRU算法
Android同样提供了HashMap和LinkedHashMap,而且总体思路有些类似,但是实现的细节明显不同。而且Android提供的LruCache虽然使用了LinkedHashMap,但是实现的思路并不一样。Java需要重写removeEldestEntry来判断是否删除节点;而Android需要重写LruCache的sizeOf,返回当前节点的大小,Android会根据这个大小判断是否超出了限制,进行调用trimToSize方法清除多余的节点。
Android的sizeOf方法默认返回1,默认的方式是判断HashMap中的数据个数是否超出了设置的阈值。也可以重写sizeOf方法,返回当前节点的大小。Android的safeSizeOf会调用sizeOf方法,其他判断阈值的方法会调用safeSizeOf方法,进行加减操作并判断阈值。进而判断是否需要清除节点。
Java的removeEldestEntry方法,也可以达到同样的效果。Java需要使用者自己提供整个判断的过程,两者思路还是有些区别的。
sizeOf,safeSizeOf不需要说明,而put和get方法,虽然和Java的实现方式不完全一样,但是思路是相同的,也不需要分析。在LruCache中put方法的最后,会调用trimToSize方法,这个方法用于清除超出的节点。它的代码如下:
publicvoidtrimToSize(intmaxSize)
{
while(true)
{
Objectkey;
Objectvalue;
synchronized(this){
if((this.size<0)||((this.map.isEmpty())&&(this.size!=0))){
thrownewIllegalStateException(getClass().getName()+".sizeOf()isreportinginconsistentresults!");
}
if(size<=maxSize){
break;
}
Map.EntrytoEvict=(Map.Entry)this.map.entrySet().iterator().next();
key=toEvict.getKey();
value=toEvict.getValue();
this.map.remove(key);
this.size-=safeSizeOf(key,value);
this.evictionCount+=1;
}
entryRemoved(true,key,value,null);
}
}
重点需要说明的是Map.EntrytoEvict=(Map.Entry)this.map.entrySet().iterator().next();这行代码。它前面的代码判断是否需要删除最近最不常使用的节点,后面的代码用于删除具体的节点。这行代码用于获取最近最不常使用的节点。
首先需要说明的问题是,Android的LinkedHashMap和Java的LinkedHashMap在思路上一样,也是使用header保存双向链表。在put和get的时候,会更新对应的节点,保存header.after指向最久没有使用的节点;header.before用于指向刚刚使用过的节点。所以Map.EntrytoEvict=(Map.Entry)this.map.entrySet().iterator().next();这行最终肯定是获取header.after节点。下面逐步分析代码,就可以看到是如何实现的了。
首先,map.entrySet(),HashMap定义了这个方法,LinkedHashMap没有重写这个方法。因此调用的是HashMap对应的方法:
publicSet<Entry<K,V>>entrySet(){
Set<Entry<K,V>>es=entrySet;
return(es!=null)?es:(entrySet=newEntrySet());
}
上面代码不需要细说,new一个EntrySet类的实例。而EntrySet也是在HashMap中定义,LinkedHashMap中没有。
privatefinalclassEntrySetextendsAbstractSet<Entry<K,V>>{
publicIterator<Entry<K,V>>iterator(){
returnnewEntryIterator();
}
publicbooleancontains(Objecto){
if(!(oinstanceofEntry))
returnfalse;
Entry<?,?>e=(Entry<?,?>)o;
returncontainsMapping(e.getKey(),e.getValue());
}
publicbooleanremove(Objecto){
if(!(oinstanceofEntry))
returnfalse;
Entry<?,?>e=(Entry<?,?>)o;
returnremoveMapping(e.getKey(),e.getValue());
}
publicintsize(){
returnsize;
}
publicbooleanisEmpty(){
returnsize==0;
}
publicvoidclear(){
HashMap.this.clear();
}
}
Iterator<Entry<K,V>>newEntryIterator(){returnnewEntryIterator();}
代码中很明显的可以看出,Map.EntrytoEvict=(Map.Entry)this.map.entrySet().iterator().next(),就是要调用
newEntryIterator().next(),就是调用(newEntryIterator()).next()。而EntryIterator类在LinkedHashMap中是有定义的。
privatefinalclassEntryIterator
extendsLinkedHashIterator<Map.Entry<K,V>>{
publicfinalMap.Entry<K,V>next(){returnnextEntry();}
}
privateabstractclassLinkedHashIterator<T>implementsIterator<T>{
LinkedEntry<K,V>next=header.nxt;
LinkedEntry<K,V>lastReturned=null;
intexpectedModCount=modCount;
publicfinalbooleanhasNext(){
returnnext!=header;
}
finalLinkedEntry<K,V>nextEntry(){
if(modCount!=expectedModCount)
thrownewConcurrentModificationException();
LinkedEntry<K,V>e=next;
if(e==header)
thrownewNoSuchElementException();
next=e.nxt;
returnlastReturned=e;
}
publicfinalvoidremove(){
if(modCount!=expectedModCount)
thrownewConcurrentModificationException();
if(lastReturned==null)
thrownewIllegalStateException();
LinkedHashMap.this.remove(lastReturned.key);
lastReturned=null;
expectedModCount=modCount;
}
}
现在可以得到结论,trimToSize中的那行代码得到的就是header.next对应的节点,也就是最近最不常使用的那个节点。
以上就是对AndroidJavaLRU缓存的实现原理做的详解,后续继续补充相关资料,谢谢大家对本站的支持!