android中图片的三级cache策略(内存、文件、网络)之二:内存缓存策略 .

来源:互联网 发布:tortoisesvn是什么软件 编辑:程序博客网 时间:2024/05/02 02:02

内存缓存策略

当有一个图片要去从网络下载的时候,我们并不会直接去从网络下载,因为在这个时代,用户的流量是宝贵的,耗流量的应用是不会得到用户的青睐的。那我们该怎么办呢?这样,我们会先从内存缓存中去查找是否有该图片,如果没有就去文件缓存中查找是否有该图片,如果还没有,我们就从网络下载图片。本博文的侧重点是如何做内存缓存,内存缓存的查找策略是:先从强引用缓存中查找,如果没有再从软引用缓存中查找,如果在软引用缓存中找到了,就把它移入强引用缓存;如果强引用缓存满了,就会根据Lru算法把某些图片移入软引用缓存,如果软引用缓存也满了,最早的软引用就会被删除。这里,我有必要说明下几个概念:强引用、软引用、弱引用、Lru。

强引用:就是直接引用一个对象,一般的对象引用均是强引用

软引用:引用一个对象,当内存不足并且除了我们的引用之外没有其他地方引用此对象的情况 下,该对象会被gc回收

弱引用:引用一个对象,当除了我们的引用之外没有其他地方引用此对象的情况下,只要gc被调用,它就会被回收(请注意它和软引用的区别)

Lru:Least Recently Used 近期最少使用算法,是一种页面置换算法,其思想是在缓存的页面数目固定的情况下,那些最近使用次数最少的页面将被移出,对于我们的内存缓存来说,强引用缓存大小固定为4M,如果当缓存的图片大于4M的时候,有些图片就会被从强引用缓存中删除,哪些图片会被删除呢,就是那些近期使用次数最少的图片。

代码

[java] view plaincopyprint?
  1. public class ImageMemoryCache {  
  2.     /** 
  3.      * 从内存读取数据速度是最快的,为了更大限度使用内存,这里使用了两层缓存。 
  4.      *  强引用缓存不会轻易被回收,用来保存常用数据,不常用的转入软引用缓存。 
  5.      */  
  6.     private static final String TAG = "ImageMemoryCache";  
  7.   
  8.     private static LruCache<String, Bitmap> mLruCache; // 强引用缓存  
  9.   
  10.     private static LinkedHashMap<String, SoftReference<Bitmap>> mSoftCache; // 软引用缓存  
  11.   
  12.     private static final int LRU_CACHE_SIZE = 4 * 1024 * 1024// 强引用缓存容量:4MB  
  13.   
  14.     private static final int SOFT_CACHE_NUM = 20// 软引用缓存个数  
  15.   
  16.     // 在这里分别初始化强引用缓存和弱引用缓存   
  17.     public ImageMemoryCache() {  
  18.         mLruCache = new LruCache<String, Bitmap>(LRU_CACHE_SIZE) {  
  19.             @Override  
  20.             // sizeOf返回为单个hashmap value的大小   
  21.             protected int sizeOf(String key, Bitmap value) {  
  22.                 if (value != null)  
  23.                     return value.getRowBytes() * value.getHeight();  
  24.                 else  
  25.                     return 0;  
  26.             }  
  27.   
  28.             @Override  
  29.             protected void entryRemoved(boolean evicted, String key,  
  30.                     Bitmap oldValue, Bitmap newValue) {  
  31.                 if (oldValue != null) {  
  32.                     // 强引用缓存容量满的时候,会根据LRU算法把最近没有被使用的图片转入此软引用缓存  
  33.                     Logger.d(TAG, "LruCache is full,move to SoftRefernceCache");  
  34.                     mSoftCache.put(key, new SoftReference<Bitmap>(oldValue));  
  35.                 }  
  36.             }  
  37.         };  
  38.   
  39.         mSoftCache = new LinkedHashMap<String, SoftReference<Bitmap>>(  
  40.                 SOFT_CACHE_NUM, 0.75f, true) {  
  41.             private static final long serialVersionUID = 1L;  
  42.   
  43.             /** 
  44.              * 当软引用数量大于20的时候,最旧的软引用将会被从链式哈希表中移出 
  45.              */  
  46.             @Override  
  47.             protected boolean removeEldestEntry(  
  48.                     Entry<String, SoftReference<Bitmap>> eldest) {  
  49.                 if (size() > SOFT_CACHE_NUM) {  
  50.                     Logger.d(TAG, "should remove the eldest from SoftReference");  
  51.                     return true;  
  52.                 }  
  53.                 return false;  
  54.             }  
  55.         };  
  56.     }  
  57.   
  58.     /** 
  59.      * 从缓存中获取图片 
  60.      */  
  61.     public Bitmap getBitmapFromMemory(String url) {  
  62.         Bitmap bitmap;  
  63.   
  64.         // 先从强引用缓存中获取   
  65.         synchronized (mLruCache) {  
  66.             bitmap = mLruCache.get(url);  
  67.             if (bitmap != null) {  
  68.                 // 如果找到的话,把元素移到LinkedHashMap的最前面,从而保证在LRU算法中是最后被删除  
  69.                 mLruCache.remove(url);  
  70.                 mLruCache.put(url, bitmap);  
  71.                 Logger.d(TAG, "get bmp from LruCache,url=" + url);  
  72.                 return bitmap;  
  73.             }  
  74.         }  
  75.   
  76.         // 如果强引用缓存中找不到,到软引用缓存中找,找到后就把它从软引用中移到强引用缓存中   
  77.         synchronized (mSoftCache) {  
  78.             SoftReference<Bitmap> bitmapReference = mSoftCache.get(url);  
  79.             if (bitmapReference != null) {  
  80.                 bitmap = bitmapReference.get();  
  81.                 if (bitmap != null) {  
  82.                     // 将图片移回LruCache   
  83.                     mLruCache.put(url, bitmap);  
  84.                     mSoftCache.remove(url);  
  85.                     Logger.d(TAG, "get bmp from SoftReferenceCache, url=" + url);  
  86.                     return bitmap;  
  87.                 } else {  
  88.                     mSoftCache.remove(url);  
  89.                 }  
  90.             }  
  91.         }  
  92.         return null;  
  93.     }  
  94.   
  95.     /** 
  96.      * 添加图片到缓存 
  97.      */  
  98.     public void addBitmapToMemory(String url, Bitmap bitmap) {  
  99.         if (bitmap != null) {  
  100.             synchronized (mLruCache) {  
  101.                 mLruCache.put(url, bitmap);  
  102.             }  
  103.         }  
  104.     }  
  105.   
  106.     public void clearCache() {  
  107.         mSoftCache.clear();  
  108.     }  
  109. }  

另外,给出LruCache供大家参考:

[java] view plaincopyprint?
  1. /* 
  2.  * Copyright (C) 2011 The Android Open Source Project 
  3.  * 
  4.  * Licensed under the Apache License, Version 2.0 (the "License"); 
  5.  * you may not use this file except in compliance with the License. 
  6.  * You may obtain a copy of the License at 
  7.  * 
  8.  *      http://www.apache.org/licenses/LICENSE-2.0 
  9.  * 
  10.  * Unless required by applicable law or agreed to in writing, software 
  11.  * distributed under the License is distributed on an "AS IS" BASIS, 
  12.  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
  13.  * See the License for the specific language governing permissions and 
  14.  * limitations under the License. 
  15.  */  
  16.   
  17. /** 
  18.  * Cache保存一个强引用来限制内容数量,每当Item被访问的时候,此Item就会移动到队列的头部。 
  19.  * 当cache已满的时候加入新的item时,在队列尾部的item会被回收。 
  20.  *  
  21.  * 如果你cache的某个值需要明确释放,重写entryRemoved() 
  22.  *  
  23.  * 如果key相对应的item丢掉啦,重写create().这简化了调用代码,即使丢失了也总会返回。 
  24.  *  
  25.  * 默认cache大小是测量的item的数量,重写sizeof计算不同item的大小。 
  26.  *   
  27.  * <pre>   {@code 
  28.  *   int cacheSize = 4 * 1024 * 1024; // 4MiB 
  29.  *   LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) { 
  30.  *       protected int sizeOf(String key, Bitmap value) { 
  31.  *           return value.getByteCount(); 
  32.  *       } 
  33.  *   }}</pre> 
  34.  * 
  35.  * <p>This class is thread-safe. Perform multiple cache operations atomically by 
  36.  * synchronizing on the cache: <pre>   {@code 
  37.  *   synchronized (cache) { 
  38.  *     if (cache.get(key) == null) { 
  39.  *         cache.put(key, value); 
  40.  *     } 
  41.  *   }}</pre> 
  42.  * 
  43.  * 不允许key或者value为null 
  44.  *  当get(),put(),remove()返回值为null时,key相应的项不在cache中 
  45.  */  
  46. public class LruCache<K, V> {  
  47.     private final LinkedHashMap<K, V> map;  
  48.   
  49.     /** Size of this cache in units. Not necessarily the number of elements. */  
  50.     private int size;//已经存储的大小  
  51.     private int maxSize;//规定的最大存储空间  
  52.   
  53.     private int putCount;//put的次数  
  54.     private int createCount;//create的次数  
  55.     private int evictionCount; //回收的次数  
  56.     private int hitCount;//命中的次数  
  57.     private int missCount;//丢失的次数  
  58.   
  59.     /** 
  60.      * @param maxSize for caches that do not override {@link #sizeOf}, this is 
  61.      *     the maximum number of entries in the cache. For all other caches, 
  62.      *     this is the maximum sum of the sizes of the entries in this cache. 
  63.      */  
  64.     public LruCache(int maxSize) {  
  65.         if (maxSize <= 0) {  
  66.             throw new IllegalArgumentException("maxSize <= 0");  
  67.         }  
  68.         this.maxSize = maxSize;  
  69.         this.map = new LinkedHashMap<K, V>(00.75f, true);  
  70.     }  
  71.   
  72.     /** 
  73.      *通过key返回相应的item,或者创建返回相应的item。相应的item会移动到队列的头部, 
  74.      * 如果item的value没有被cache或者不能被创建,则返回null。 
  75.      */  
  76.     public final V get(K key) {  
  77.         if (key == null) {  
  78.             throw new NullPointerException("key == null");  
  79.         }  
  80.   
  81.         V mapValue;  
  82.         synchronized (this) {  
  83.             mapValue = map.get(key);  
  84.             if (mapValue != null) {  
  85.                 hitCount++;  
  86.                 return mapValue;  
  87.             }  
  88.             missCount++;  
  89.         }  
  90.   
  91.         /* 
  92.          * Attempt to create a value. This may take a long time, and the map 
  93.          * may be different when create() returns. If a conflicting value was 
  94.          * added to the map while create() was working, we leave that value in 
  95.          * the map and release the created value. 
  96.          */  
  97.   
  98.         V createdValue = create(key);  
  99.         if (createdValue == null) {  
  100.             return null;  
  101.         }  
  102.   
  103.         synchronized (this) {  
  104.             createCount++;  
  105.             mapValue = map.put(key, createdValue);  
  106.   
  107.             if (mapValue != null) {  
  108.                 // There was a conflict so undo that last put  
  109.                 map.put(key, mapValue);  
  110.             } else {  
  111.                 size += safeSizeOf(key, createdValue);  
  112.             }  
  113.         }  
  114.   
  115.         if (mapValue != null) {  
  116.             entryRemoved(false, key, createdValue, mapValue);  
  117.             return mapValue;  
  118.         } else {  
  119.             trimToSize(maxSize);  
  120.             return createdValue;  
  121.         }  
  122.     }  
  123.   
  124.     /** 
  125.      * Caches {@code value} for {@code key}. The value is moved to the head of 
  126.      * the queue. 
  127.      * 
  128.      * @return the previous value mapped by {@code key}. 
  129.      */  
  130.     public final V put(K key, V value) {  
  131.         if (key == null || value == null) {  
  132.             throw new NullPointerException("key == null || value == null");  
  133.         }  
  134.   
  135.         V previous;  
  136.         synchronized (this) {  
  137.             putCount++;  
  138.             size += safeSizeOf(key, value);  
  139.             previous = map.put(key, value);  
  140.             if (previous != null) {  
  141.                 size -= safeSizeOf(key, previous);  
  142.             }  
  143.         }  
  144.   
  145.         if (previous != null) {  
  146.             entryRemoved(false, key, previous, value);  
  147.         }  
  148.   
  149.         trimToSize(maxSize);  
  150.         return previous;  
  151.     }  
  152.   
  153.     /** 
  154.      * @param maxSize the maximum size of the cache before returning. May be -1 
  155.      *     to evict even 0-sized elements. 
  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.                 /* 
  172.                  * Map.Entry<K, V> toEvict = map.eldest();                
  173.                  */  
  174.                 //modify by echy   
  175.                   
  176.                 Iterator<Entry<K, V>> iter = map.entrySet().iterator();   
  177.                 Map.Entry<K, V> toEvict = null;  
  178.                 while (iter.hasNext())   
  179.                 {  
  180.                       
  181.                     toEvict = (Entry<K, V>) iter.next();  
  182.                     break;  
  183.                 }  
  184.                   
  185.                   
  186.                 if (toEvict == null) {  
  187.                     break;  
  188.                 }  
  189.                   
  190.                 key = toEvict.getKey();  
  191.                 value = toEvict.getValue();  
  192.                   
  193.                   
  194.                 map.remove(key);  
  195.                 size -= safeSizeOf(key, value);  
  196.                 evictionCount++;  
  197.             }  
  198.   
  199.             entryRemoved(true, key, value, null);  
  200.         }  
  201.     }  
  202.   
  203.     /** 
  204.      * Removes the entry for {@code key} if it exists. 
  205.      * 
  206.      * @return the previous value mapped by {@code key}. 
  207.      */  
  208.     public final V remove(K key) {  
  209.         if (key == null) {  
  210.             throw new NullPointerException("key == null");  
  211.         }  
  212.   
  213.         V previous;  
  214.         synchronized (this) {  
  215.             previous = map.remove(key);  
  216.             if (previous != null) {  
  217.                 size -= safeSizeOf(key, previous);  
  218.             }  
  219.         }  
  220.   
  221.         if (previous != null) {  
  222.             entryRemoved(false, key, previous, null);  
  223.         }  
  224.   
  225.         return previous;  
  226.     }  
  227.   
  228.     /** 
  229.      * Called for entries that have been evicted or removed. This method is 
  230.      * invoked when a value is evicted to make space, removed by a call to 
  231.      * {@link #remove}, or replaced by a call to {@link #put}. The default 
  232.      * implementation does nothing. 
  233.      * 
  234.      * <p>The method is called without synchronization: other threads may 
  235.      * access the cache while this method is executing. 
  236.      * 
  237.      * @param evicted true if the entry is being removed to make space, false 
  238.      *     if the removal was caused by a {@link #put} or {@link #remove}. 
  239.      * @param newValue the new value for {@code key}, if it exists. If non-null, 
  240.      *     this removal was caused by a {@link #put}. Otherwise it was caused by 
  241.      *     an eviction or a {@link #remove}. 
  242.      */  
  243.     protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) {}  
  244.   
  245.     /** 
  246.      * Called after a cache miss to compute a value for the corresponding key. 
  247.      * Returns the computed value or null if no value can be computed. The 
  248.      * default implementation returns null. 
  249.      * 
  250.      * <p>The method is called without synchronization: other threads may 
  251.      * access the cache while this method is executing. 
  252.      * 
  253.      * <p>If a value for {@code key} exists in the cache when this method 
  254.      * returns, the created value will be released with {@link #entryRemoved} 
  255.      * and discarded. This can occur when multiple threads request the same key 
  256.      * at the same time (causing multiple values to be created), or when one 
  257.      * thread calls {@link #put} while another is creating a value for the same 
  258.      * key. 
  259.      */  
  260.     protected V create(K key) {  
  261.         return null;  
  262.     }  
  263.   
  264.     private int safeSizeOf(K key, V value) {  
  265.         int result = sizeOf(key, value);  
  266.         if (result < 0) {  
  267.             throw new IllegalStateException("Negative size: " + key + "=" + value);  
  268.         }  
  269.         return result;  
  270.     }  
  271.   
  272.     /** 
  273.      * Returns the size of the entry for {@code key} and {@code value} in 
  274.      * user-defined units.  The default implementation returns 1 so that size 
  275.      * is the number of entries and max size is the maximum number of entries. 
  276.      * 
  277.      * <p>An entry's size must not change while it is in the cache. 
  278.      */  
  279.     protected int sizeOf(K key, V value) {  
  280.         return 1;  
  281.     }  
  282.   
  283.     /** 
  284.      * Clear the cache, calling {@link #entryRemoved} on each removed entry. 
  285.      */  
  286.     public final void evictAll() {  
  287.         trimToSize(-1); // -1 will evict 0-sized elements  
  288.     }  
  289.   
  290.     /** 
  291.      * For caches that do not override {@link #sizeOf}, this returns the number 
  292.      * of entries in the cache. For all other caches, this returns the sum of 
  293.      * the sizes of the entries in this cache. 
  294.      */  
  295.     public synchronized final int size() {  
  296.         return size;  
  297.     }  
  298.   
  299.     /** 
  300.      * For caches that do not override {@link #sizeOf}, this returns the maximum 
  301.      * number of entries in the cache. For all other caches, this returns the 
  302.      * maximum sum of the sizes of the entries in this cache. 
  303.      */  
  304.     public synchronized final int maxSize() {  
  305.         return maxSize;  
  306.     }  
  307.   
  308.     /** 
  309.      * Returns the number of times {@link #get} returned a value that was 
  310.      * already present in the cache. 
  311.      */  
  312.     public synchronized final int hitCount() {  
  313.         return hitCount;  
  314.     }  
  315.   
  316.     /** 
  317.      * Returns the number of times {@link #get} returned null or required a new 
  318.      * value to be created. 
  319.      */  
  320.     public synchronized final int missCount() {  
  321.         return missCount;  
  322.     }  
  323.   
  324.     /** 
  325.      * Returns the number of times {@link #create(Object)} returned a value. 
  326.      */  
  327.     public synchronized final int createCount() {  
  328.         return createCount;  
  329.     }  
  330.   
  331.     /** 
  332.      * Returns the number of times {@link #put} was called. 
  333.      */  
  334.     public synchronized final int putCount() {  
  335.         return putCount;  
  336.     }  
  337.   
  338.     /** 
  339.      * Returns the number of values that have been evicted. 
  340.      */  
  341.     public synchronized final int evictionCount() {  
  342.         return evictionCount;  
  343.     }  
  344.   
  345.     /** 
  346.      * Returns a copy of the current contents of the cache, ordered from least 
  347.      * recently accessed to most recently accessed. 
  348.      */  
  349.     public synchronized final Map<K, V> snapshot() {  
  350.         return new LinkedHashMap<K, V>(map);  
  351.     }  
  352.   
  353.     @Override public synchronized final String toString() {  
  354.         int accesses = hitCount + missCount;  
  355.         int hitPercent = accesses != 0 ? (100 * hitCount / accesses) : 0;  
  356.         return String.format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]",  
  357.                 maxSize, hitCount, missCount, hitPercent);  
  358.     }  
  359. }  
0 0
原创粉丝点击