一、LRU是什么
Least Recently Used,也就是最近最少使用,LRU缓存将最近最少使用的数据移除,让给最新读取的数据。而往往是最常读取的,也就是读取次数最多的。所以利用LRU缓存,我们可能提高系统的performance.
二、LRU的实现
使用LinkedHashMap的好处:

代码如下
public class MyLRUCache1<K,V>{
private static final float hashTableLoadFactor = 0.75f;
private LinkedHashMap<K,V > map ;
private int cacheSize ;
public MyLRUCache1( int cacheSize){
this.cacheSize = cacheSize ;
int hashTableCapacity = (int)Math.ceil(cacheSize/hashTableLoadFactor)+1;
//an anonymous inner class,true means accessOrder
map = new LinkedHashMap<K,V>(hashTableCapacity, hashTableLoadFactor, true) {
private static final long serialVersionID=1;
@Override
protected boolean removeEldestEntry(Entry<K, V> eldest) {
//在什么情况下进行回收
return size()> MyLRUCache1.this.cacheSize ;
}
};
}
public synchronized V get(K key){
return map.get(key) ;
}
public synchronized void put(K key,V value){
map.put(key, value) ;
}
public synchronized void clear (){
map.clear();
}
public synchronized int usedEntries(){
return map.size() ;
}
public synchronized Collection<Map.Entry<K,V>> getAll(){
return new ArrayList<Map.Entry<K,V>>(map.entrySet()) ;
}
}
测试方法
StringBuilder sb = new StringBuilder() ;
cache.put("1", "one"); //1
cache.put("2", "two"); //2 1
cache.put("3", "three"); //3 2 1
cache.put("4", "four"); //4 3 2
if (cache.get("2")== null)
throw new Error() ; //2 4 3
for (Map.Entry<String,String > e : cache.getAll()){
sb.append(e.getKey()+":"+e.getValue()+"\n");
}
cache.put("5", "five"); //5 2 4
cache.put("4", "second four");//4 5 2
//verify cache content
sb.append("cache used:"+cache.usedEntries()+"\n") ;
sb.append(cache.get("4")+"\n");
sb.append(cache.get("5")+"\n");
sb.append(cache.get("2")+"\n");
for (Map.Entry<String,String > e : cache.getAll()){
sb.append(e.getKey()+":"+e.getValue()+"\n");
}
tv.setText(sb.toString());
Log.d(TAG,sb.toString()) ;
结果如下
3:three
4:four
2:two
cache used:3
second four
five
two
4:second four
5:five
2:two
原文:http://www.cnblogs.com/chuiyuan/p/4836877.html