LRUCache原理

       讲到LruCache不得不提一下LinkedHashMap,因为LruCache中Lru算法的实现就是通过LinkedHashMap来实现的。LinkedHashMap继承于HashMap,它使用了一个双向链表来存储Map中的Entry顺序关系,这种顺序有两种,一种是LRU顺序,一种是插入顺序,这可以由其构造函数public LinkedHashMap(int initialCapacity,float loadFactor, boolean accessOrder)指定。所以,对于get、put、remove等操作,LinkedHashMap除了要做HashMap做的事情,还做些调整Entry顺序链表的工作。LruCache中将LinkedHashMap的顺序设置为LRU顺序来实现LRU缓存,每次调用get(也就是从内存缓存中取图片),则将该对象移到链表的尾端。调用put插入新的对象也是存储在链表尾端,这样当内存缓存达到设定的最大值时,将链表头部的对象(近期最少用到的)移除。

/*

 *Copyright (C) 2011 The Android Open Source Project

 *

 *Licensed under the Apache License, Version 2.0 (the "License");

 *you may not use this file except in compliance with the License.

 *You may obtain a copy of the License at

 *

 *     http://www.apache.org/licenses/LICENSE-2.0

 *

 *Unless required by applicable law or agreed to in writing, software

 *distributed under the License is distributed on an "AS IS" BASIS,

 *WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.

 *See the License for the specific language governing permissions and

 *limitations under the License.

 */


package android.support.v4.util;


import java.util.LinkedHashMap;

import java.util.Map;


/**

 *Static library version of {@link android.util.LruCache}. Used to write apps

 *that run on API levels prior to 12. When running on API level 12 or above,

 *this implementation is still used; it does not try to switch to the

 *framework's implementation. See the framework SDK documentation for a class

 *overview.

 */

public class LruCache {

   private final LinkedHashMap map;


   /** Size of this cache in units. Not necessarily the number of elements.*/

   private int size;    //当前cache的大小

   private int maxSize; //cache最大大小


   private int putCount;       //put的次数

   private int createCount;   //create的次数

   private int evictionCount;  //回收的次数

   private int hitCount;       //命中的次数

   private int missCount;      //未命中次数


   /**

     * @param maxSize for caches that do notoverride {@link #sizeOf}, this is

    *     the maximum number ofentries in the cache. For all other caches,

    *     this is the maximum sum ofthe sizes of the entries in this cache.

    */

   public LruCache(int maxSize) {

       if (maxSize <= 0) {

           throw new IllegalArgumentException("maxSize <= 0");

       }

       this.maxSize = maxSize;

       //将LinkedHashMap的accessOrder设置为true来实现LRU

       this.map = new LinkedHashMap(0, 0.75f, true); 

    }


   /**

    * Returns the value for {@code key} if it exists in the cache or can be

    * created by {@code #create}. If a value was returned, it is moved tothe

    * head of the queue. This returns null if a value is not cached andcannot

    * be created.

    *通过key获取相应的item,或者创建返回相应的item。相应的item会移动到队列的尾部,

    *如果item的value没有被cache或者不能被创建,则返回null。

    */

   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) {

                //mapValue不为空表示命中,hitCount+1并返回mapValue对象

                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.

        *如果未命中,则试图创建一个对象,这里create方法返回null,并没有实现创建对象的方法

        *如果需要事项创建对象的方法可以重写create方法。因为图片缓存时内存缓存没有命中会去

        *文件缓存中去取或者从网络下载,所以并不需要创建。

        */

       V createdValue = create(key);

       if (createdValue == null) {

           return null;

       }

       //假如创建了新的对象,则继续往下执行

       synchronized (this) {

           createCount++; 

           //将createdValue加入到map中,并且将原来键为key的对象保存到mapValue

           mapValue = map.put(key, createdValue);  

           if (mapValue != null) {

                // There was a conflict so undothat last put

                //如果mapValue不为空,则撤销上一步的put操作。

                map.put(key, mapValue);

           } else {

                //加入新创建的对象之后需要重新计算size大小

                size += safeSizeOf(key,createdValue);

           }

       }


       if (mapValue != null) {

           entryRemoved(false, key, createdValue, mapValue);

           return mapValue;

       } else {

           //每次新加入对象都需要调用trimToSize方法看是否需要回收

           trimToSize(maxSize);

           return createdValue;

       }

    }


   /**

    * Caches {@code value} for {@code key}. The value is moved to the headof

    * the queue.

    *

    * @return the previous value mapped by {@code key}.

    */

   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); //size加上预put对象的大小

           previous = map.put(key, value);

           if (previous != null) {

                //如果之前存在键为key的对象,则size应该减去原来对象的大小

               size -= safeSizeOf(key,previous);

           }

       }


       if (previous != null) {

           entryRemoved(false, key, previous, value);

       }

       //每次新加入对象都需要调用trimToSize方法看是否需要回收

       trimToSize(maxSize);

       return previous;

    }


   /**

    * @param maxSize the maximum size of the cache before returning. May be-1

    *     to evict even 0-sizedelements.

    *此方法根据maxSize来调整内存cache的大小,如果maxSize传入-1,则清空缓存中的所有对象

    */

   private void trimToSize(int maxSize) {

       while (true) {

           K key;

           V value;

           synchronized (this) {

                if (size < 0 ||(map.isEmpty() && size != 0)) {

                    throw newIllegalStateException(getClass().getName()

                            + ".sizeOf() is reportinginconsistent results!");

                }

                //如果当前size小于maxSize或者map没有任何对象,则结束循环

                if (size <= maxSize ||map.isEmpty()) {

                    break;

                }

                //移除链表头部的元素,并进入下一次循环

                Map.Entry toEvict =map.entrySet().iterator().next();

                key = toEvict.getKey();

                value = toEvict.getValue();

                map.remove(key);

                size -= safeSizeOf(key, value);

                evictionCount++;  //回收次数+1

           }


           entryRemoved(true, key, value, null);

       }

    }


   /**

    * Removes the entry for {@code key} if it exists.

    *

    * @return the previous value mapped by {@code key}.

    *从内存缓存中根据key值移除某个对象并返回该对象

    */

   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;

    }


   /**

    * Called for entries that have been evicted or removed. This method is

    * invoked when a value is evicted to make space, removed by a call to

    * {@link #remove}, or replaced by a call to {@link #put}. The default

    * implementation does nothing.

    *

    *

The method is called without synchronization: other threadsmay

    * access the cache while this method is executing.

    *

    * @param evicted true if the entry is being removed to make space, false

    *     if the removal was caused bya {@link #put} or {@link #remove}.

    * @param newValue the new value for {@code key}, if it exists. Ifnon-null,

    *     this removal was caused by a{@link #put}. Otherwise it was caused by

    *     an eviction or a {@link#remove}.

     */

   protected void entryRemoved(boolean evicted, K key, V oldValue, VnewValue) {}


   /**

    * Called after a cache miss to compute a value for the correspondingkey.

    * Returns the computed value or null if no value can be computed. The

     * default implementation returns null.

    *

    *

The method is called without synchronization: other threadsmay

    * access the cache while this method is executing.

    *

    *

If a value for {@code key} exists in the cache when thismethod

    * returns, the created value will be released with {@link #entryRemoved}

    * and discarded. This can occur when multiple threads request the samekey

    * at the same time (causing multiple values to be created), or when one

    * thread calls {@link #put} while another is creating a value for thesame

    * key.

    */

   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;

    }


   /**

    * Returns the size of the entry for {@code key} and {@code value} in

    * user-defined units.  The defaultimplementation returns 1 so that size

    * is the number of entries and max size is the maximum number ofentries.

    *

    *

An entry's size must not change while it is in the cache.

    *用来计算单个对象的大小,这里默认返回1,一般需要重写该方法来计算对象的大小

    * xUtils中创建LruMemoryCache时就重写了sizeOf方法来计算bitmap的大小

    * mMemoryCache = new LruMemoryCache(globalConfig.getMemoryCacheSize()) {

    *       @Override

    *       protected intsizeOf(MemoryCacheKey key, Bitmap bitmap) {

    *           if (bitmap == null)return 0;

    *           returnbitmap.getRowBytes() * bitmap.getHeight();

    *       }

    *   };

    *

    */

   protected int sizeOf(K key, V value) {

       return 1;

    }


   /**

    * Clear the cache, calling {@link #entryRemoved} on each removed entry.

    *清空内存缓存

    */

   public final void evictAll() {

       trimToSize(-1); // -1 will evict 0-sized elements

    }


   /**

    * For caches that do not override {@link #sizeOf}, this returns thenumber

    * of entries in the cache. For all other caches, this returns the sum of

    * the sizes of the entries in this cache.

    */

   public synchronized final int size() {

       return size;

    }


   /**

    * For caches that do not override {@link #sizeOf}, this returns themaximum

    * number of entries in the cache. For all other caches, this returns the

    * maximum sum of the sizes of the entries in this cache.

    */

   public synchronized final int maxSize() {

       return maxSize;

    }


   /**

    * Returns the number of times {@link #get} returned a value.

    */

   public synchronized final int hitCount() {

       return hitCount;

    }


   /**

    * Returns the number of times {@link #get} returned null or required anew

    * value to be created.

    */

   public synchronized final int missCount() {

       return missCount;

    }


   /**

    * Returns the number of times {@link #create(Object)} returned a value.

    */

   public synchronized final int createCount() {

       return createCount;

    }


   /**

    * Returns the number of times {@link #put} was called.

    */

   public synchronized final int putCount() {

       return putCount;

    }


   /**

    * Returns the number of values that have been evicted.

    */

   public synchronized final int evictionCount() {

       return evictionCount;

    }


   /**

    * Returns a copy of the current contents of the cache, ordered fromleast

    * recently accessed to most recently accessed.

    */

   public synchronized final Map snapshot() {

       return new LinkedHashMap(map);

    }


   @Override public synchronized final String toString() {

        int accesses = hitCount + missCount;

       int hitPercent = accesses != 0 ? (100 * hitCount / accesses) : 0;

       returnString.format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]",

                maxSize, hitCount, missCount,hitPercent);

    }

}

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,106评论 0 10
  • Lua 5.1 参考手册 by Roberto Ierusalimschy, Luiz Henrique de F...
    苏黎九歌阅读 13,517评论 0 38
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • 我们之前看到了函数和对象。从本质上来说,它们都是为了更好的组织已经有的程序,以方便重复使用。 模块(module)...
    L小橙子阅读 218评论 0 0
  • 最近刷微博比较多,总是有些博文说一见钟情并不单单是钟情于对方的脸,而且是非常有道理的。具体的内容我已经记不清了,大...
    仄十七阅读 314评论 0 1