LruCache

public class

LruCache

extends  Object
java.lang.Object
   ↳ android.util.LruCache<K, V>

Class Overview


A cache that holds strong references to a limited number of values. Each time a value is accessed, it is moved to the head of a queue. When a value is added to a full cache, the value at the end of that queue is evicted and may become eligible for garbage collection.

If your cached values hold resources that need to be explicitly released, override entryRemoved(boolean, K, V, V).

If a cache miss should be computed on demand for the corresponding keys, override create(K). This simplifies the calling code, allowing it to assume a value will always be returned, even when there's a cache miss.

By default, the cache size is measured in the number of entries. Override sizeOf(K, V) to size the cache in different units. For example, this cache is limited to 4MiB of bitmaps:

   int cacheSize = 4 * 1024 * 1024; // 4MiB
   LruCache bitmapCache = new LruCache(cacheSize) {
       protected int sizeOf(String key, Bitmap value) {
           return value.getByteCount();
       
   }}

This class is thread-safe. Perform multiple cache operations atomically by synchronizing on the cache:

   synchronized (cache) {
     if (cache.get(key) == null) {
         cache.put(key, value);
     
   }}

This class does not allow null to be used as a key or value. A return value of null from get(K)put(K, V) or remove(K) is unambiguous: the key was not in the cache.

This class appeared in Android 3.1 (Honeycomb MR1); it's available as part of Android's Support Package for earlier releases.


LruCache 具体实现

  1. package android.util;  
  2.   
  3. import java.util.LinkedHashMap;  
  4. import java.util.Map;  
  5.   
  6. /** 
  7.  * A cache that holds strong references to a limited number of values. Each time 
  8.  * a value is accessed, it is moved to the head of a queue. When a value is 
  9.  * added to a full cache, the value at the end of that queue is evicted and may 
  10.  * become eligible for garbage collection. 
  11.  *
  12.  * <p>If your cached values hold resources that need to be explicitly released, 
  13.  * override {@link #entryRemoved}. 
  14.  * <p>If a cache miss should be computed on demand for the corresponding keys, 
  15.  * override {@link #create}. This simplifies the calling code, allowing it to 
  16.  * assume a value will always be returned, even when there's a cache miss. 
  17.  * <p>By default, the cache size is measured in the number of entries. Override 
  18.  * {@link #sizeOf} to size the cache in different units. For example, this cache 
  19.  * is limited to 4MiB of bitmaps: 
  20.  * <pre>   {@code 
  21.  *   int cacheSize = 4 * 1024 * 1024; // 4MiB 
  22.  *   LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) { 
  23.  *       protected int sizeOf(String key, Bitmap value) { 
  24.  *           return value.getByteCount(); 
  25.  *       } 
  26.  *   }}</pre> 
  27.  * 
  28.  * <p>This class is thread-safe. Perform multiple cache operations atomically by 
  29.  * synchronizing on the cache: <pre>   {@code 
  30.  *   synchronized (cache) { 
  31.  *     if (cache.get(key) == null) { 
  32.  *         cache.put(key, value); 
  33.  *     } 
  34.  *   }}</pre> 
  35.  * 
  36.  * <p>This class does not allow null to be used as a key or value. A return 
  37.  * value of null from {@link #get}, {@link #put} or {@link #remove} is 
  38.  * unambiguous: the key was not in the cache.
  39.  */  
  40. public class LruCache<K, V> {  
  41.     private final LinkedHashMap<K, V> map;  
  42.   
  43.     /** Size of this cache in units. Not necessarily the number of elements. */  
  44.     private int size; //已经存储的大小
  45.     private int maxSize; //规定的最大存储空间大小
  46.   
  47.     private int putCount;  //put的次数
  48.     private int createCount;  //create的次数
  49.     private int evictionCount;  //回收的次数
  50.     private int hitCount;  //命中的次数
  51.     private int missCount;  //未命中的次数
  52.   
  53.     /** 
  54.      * @param maxSize for caches that do not override {@link #sizeOf}, this is 
  55.      *     the maximum number of entries in the cache. For all other caches, 
  56.      *     this is the maximum sum of the sizes of the entries in this cache. 
  57.      */  
  58.     public LruCache(int maxSize) {  
  59.         if (maxSize <= 0) {  
  60.             throw new IllegalArgumentException("maxSize <= 0");  
  61.         }  
  62.         this.maxSize = maxSize;  
  63.         this.map = new LinkedHashMap<K, V>(00.75f, true);  
  64.     }  
  65.   
  66.     /** 
  67.      * Returns the value for {@code key} if it exists in the cache or can be 
  68.      * created by {@code #create}. If a value was returned, it is moved to the 
  69.      * head of the queue. This returns null if a value is not cached and cannot 
  70.      * be created. 在cache中找到key对应的value,或者创建并返回(通过create)。返回的value会
  71.      * 移动到队列的头部,如果没有能在cache中找到且不能被创建,则返回null。
  72.      */  
  73.     public final V get(K key) {  
  74.         if (key == null) {  
  75.             throw new NullPointerException("key == null");  
  76.         }  
  77.   
  78.         V mapValue;  
  79.         synchronized (this) {  
  80.             mapValue = map.get(key);  
  81.             if (mapValue != null) {  
  82.                 hitCount++;  //命中
  83.                 return mapValue;  
  84.             }  
  85.             missCount++;  //未命中
  86.         }  
  87.   
  88.         /* 
  89.          * Attempt to create a value. This may take a long time, and the map 
  90.          * may be different when create() returns. If a conflicting value was 
  91.          * added to the map while create() was working, we leave that value in 
  92.          * the map and release the created value. 
  93.          * 尝试去创建value。这会花费很长时间,而其在create()返回时可能会不同。
  94.          */  
  95.   
  96.         V createdValue = create(key);  
  97.         if (createdValue == null) {  
  98.             return null;  
  99.         }  
  100.   
  101.         synchronized (this) {  
  102.             createCount++;//创建++  
  103.             mapValue = map.put(key, createdValue);  
  104.   
  105.             if (mapValue != null) {  
  106.                 // There was a conflict so undo that last put  
  107.                 // 如果前面存在冲突,撤销上次的put
  108.                 map.put(key, mapValue);  
  109.             } else {  
  110.                 size += safeSizeOf(key, createdValue);  
  111.             }  
  112.         }  
  113.   
  114.         if (mapValue != null) {  
  115.             entryRemoved(false, key, createdValue, mapValue);  
  116.             return mapValue;  
  117.         } else {  
  118.             trimToSize(maxSize);  
  119.             return createdValue;  
  120.         }  
  121.     }  
  122.   
  123.     /** 
  124.      * Caches {@code value} for {@code key}. The value is moved to the head of 
  125.      * the queue. 
  126.      * 
  127.      * @return the previous value mapped by {@code key}. 
  128.      */  
  129.     public final V put(K key, V value) {  
  130.         if (key == null || value == null) {  
  131.             throw new NullPointerException("key == null || value == null");  
  132.         }  
  133.   
  134.         V previous;  
  135.         synchronized (this) {  
  136.             putCount++;  
  137.             size += safeSizeOf(key, value);  
  138.             previous = map.put(key, value);  
  139.             if (previous != null) {  //返回的先前的value值
  140.                 size -= safeSizeOf(key, previous);  
  141.             }  
  142.         }  
  143.   
  144.         if (previous != null) {  
  145.             entryRemoved(false, key, previous, value);  
  146.         }  
  147.   
  148.         trimToSize(maxSize);  
  149.         return previous;  
  150.     }  
  151.   
  152.     /** 
  153.      * @param maxSize the maximum size of the cache before returning. May be -1 
  154.      *     to evict even 0-sized elements. 
  155.      *  清空cache空间
  156.      */  
  157.     private void trimToSize(int maxSize) {  
  158.         while (true) {  
  159.             K key;  
  160.             V value;  
  161.             synchronized (this) {  
  162.                 if (size < 0 || (map.isEmpty() && size != 0)) {  
  163.                     throw new IllegalStateException(getClass().getName()  
  164.                             + ".sizeOf() is reporting inconsistent results!");  
  165.                 }  
  166.   
  167.                 if (size <= maxSize) {  
  168.                     break;  
  169.                 }  
  170.   
  171.                 Map.Entry<K, V> toEvict = map.eldest();  
  172.                 if (toEvict == null) {  
  173.                     break;  
  174.                 }  
  175.   
  176.                 key = toEvict.getKey();  
  177.                 value = toEvict.getValue();  
  178.                 map.remove(key);  
  179.                 size -= safeSizeOf(key, value);  
  180.                 evictionCount++;  
  181.             }  
  182.   
  183.             entryRemoved(true, key, value, null);  
  184.         }  
  185.     }  
  186.   
  187.     /** 
  188.      * Removes the entry for {@code key} if it exists. 
  189.      * 删除key相应的cache项,返回相应的value
  190.      * @return the previous value mapped by {@code key}. 
  191.      */  
  192.     public final V remove(K key) {  
  193.         if (key == null) {  
  194.             throw new NullPointerException("key == null");  
  195.         }  
  196.   
  197.         V previous;  
  198.         synchronized (this) {  
  199.             previous = map.remove(key);  
  200.             if (previous != null) {  
  201.                 size -= safeSizeOf(key, previous);  
  202.             }  
  203.         }  
  204.   
  205.         if (previous != null) {  
  206.             entryRemoved(false, key, previous, null);  
  207.         }  
  208.   
  209.         return previous;  
  210.     }  
  211.   
  212.     /** 
  213.      * Called for entries that have been evicted or removed. This method is 
  214.      * invoked when a value is evicted to make space, removed by a call to 
  215.      * {@link #remove}, or replaced by a call to {@link #put}. The default 
  216.      * implementation does nothing. 
  217.      * 当item被回收或者删掉时调用。改方法当value被回收释放存储空间时被remove调用,
  218.      * 或者替换item值时put调用,默认实现什么都没做。
  219.      * <p>The method is called without synchronization: other threads may 
  220.      * access the cache while this method is executing. 
  221.      * 
  222.      * @param evicted true if the entry is being removed to make space, false 
  223.      *     if the removal was caused by a {@link #put} or {@link #remove}. 
  224.      * true---为释放空间被删除;false---put或remove导致
  225.      * @param newValue the new value for {@code key}, if it exists. If non-null, 
  226.      *     this removal was caused by a {@link #put}. Otherwise it was caused by 
  227.      *     an eviction or a {@link #remove}. 
  228.      */  
  229.     protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) {}  
  230.   
  231.     /** 
  232.      * Called after a cache miss to compute a value for the corresponding key. 
  233.      * Returns the computed value or null if no value can be computed. The 
  234.      * default implementation returns null. 
  235.      * 当某Item丢失时会调用到,返回计算的相应的value或者null
  236.      * <p>The method is called without synchronization: other threads may 
  237.      * access the cache while this method is executing. 
  238.      * 
  239.      * <p>If a value for {@code key} exists in the cache when this method 
  240.      * returns, the created value will be released with {@link #entryRemoved} 
  241.      * and discarded. This can occur when multiple threads request the same key 
  242.      * at the same time (causing multiple values to be created), or when one 
  243.      * thread calls {@link #put} while another is creating a value for the same 
  244.      * key. 
  245.      */  
  246.     protected V create(K key) {  
  247.         return null;  
  248.     }  
  249.   
  250.     private int safeSizeOf(K key, V value) {  
  251.         int result = sizeOf(key, value);  
  252.         if (result < 0) {  
  253.             throw new IllegalStateException("Negative size: " + key + "=" + value);  
  254.         }  
  255.         return result;  
  256.     }  
  257.   
  258.     /** 
  259.      * Returns the size of the entry for {@code key} and {@code value} in 
  260.      * user-defined units.  The default implementation returns 1 so that size 
  261.      * is the number of entries and max size is the maximum number of entries. 
  262.      * 返回用户定义的item的大小,默认返回1代表item的数量,最大size就是最大item值
  263.      * <p>An entry's size must not change while it is in the cache. 
  264.      */  
  265.     protected int sizeOf(K key, V value) {  
  266.         return 1;  
  267.     }  
  268.   
  269.     /** 
  270.      * Clear the cache, calling {@link #entryRemoved} on each removed entry. 
  271.      * 清空cacke
  272.      */  
  273.     public final void evictAll() {  
  274.         trimToSize(-1); // -1 will evict 0-sized elements  
  275.     }  
  276.   
  277.     /** 
  278.      * For caches that do not override {@link #sizeOf}, this returns the number 
  279.      * of entries in the cache. For all other caches, this returns the sum of 
  280.      * the sizes of the entries in this cache. 
  281.      */  
  282.     public synchronized final int size() {  
  283.         return size;  
  284.     }  
  285.   
  286.     /** 
  287.      * For caches that do not override {@link #sizeOf}, this returns the maximum 
  288.      * number of entries in the cache. For all other caches, this returns the 
  289.      * maximum sum of the sizes of the entries in this cache. 
  290.      */  
  291.     public synchronized final int maxSize() {  
  292.         return maxSize;  
  293.     }  
  294.   
  295.     /** 
  296.      * Returns the number of times {@link #get} returned a value that was 
  297.      * already present in the cache. 
  298.      */  
  299.     public synchronized final int hitCount() {  
  300.         return hitCount;  
  301.     }  
  302.   
  303.     /** 
  304.      * Returns the number of times {@link #get} returned null or required a new 
  305.      * value to be created. 
  306.      */  
  307.     public synchronized final int missCount() {  
  308.         return missCount;  
  309.     }  
  310.   
  311.     /** 
  312.      * Returns the number of times {@link #create(Object)} returned a value. 
  313.      */  
  314.     public synchronized final int createCount() {  
  315.         return createCount;  
  316.     }  
  317.   
  318.     /** 
  319.      * Returns the number of times {@link #put} was called. 
  320.      */  
  321.     public synchronized final int putCount() {  
  322.         return putCount;  
  323.     }  
  324.   
  325.     /** 
  326.      * Returns the number of values that have been evicted. 
  327.      * 返回被回收的数量
  328.      */  
  329.     public synchronized final int evictionCount() {  
  330.         return evictionCount;  
  331.     }  
  332.   
  333.     /** 
  334.      * Returns a copy of the current contents of the cache, ordered from least 
  335.      * recently accessed to most recently accessed. 返回当前cache的副本,从最近最少访问到最多访问
  336.      */  
  337.     public synchronized final Map<K, V> snapshot() {  
  338.         return new LinkedHashMap<K, V>(map);  
  339.     }  
  340.   
  341.     @Override public synchronized final String toString() {  
  342.         int accesses = hitCount + missCount;  
  343.         int hitPercent = accesses != 0 ? (100 * hitCount / accesses) : 0;  
  344.         return String.format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]",  
  345.                 maxSize, hitCount, missCount, hitPercent);  
  346.     }  
  347. }  

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值