Android提供的LruCache类简介

package android.util;  

import java.util.LinkedHashMap;
import java.util.Map;  

/**
 * 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.
 * Cache保存一个强引用来限制内容数量,每当Item被访问的时候,此Item就会移动到队列的头部。
 * 当cache已满的时候加入新的item时,在队列尾部的item会被回收。
 * <p>If your cached values hold resources that need to be explicitly released,
 * override {@link #entryRemoved}.
 * 如果你cache的某个值需要明确释放,重写entryRemoved()
 * <p>If a cache miss should be computed on demand for the corresponding keys,
 * override {@link #create}. This simplifies the calling code, allowing it to
 * assume a value will always be returned, even when there‘s a cache miss.
 * 如果key相对应的item丢掉啦,重写create().这简化了调用代码,即使丢失了也总会返回。
 * <p>By default, the cache size is measured in the number of entries. Override
 * {@link #sizeOf} to size the cache in different units. For example, this cache
 * is limited to 4MiB of bitmaps: 默认cache大小是测量的item的数量,重写sizeof计算不同item的
 *  大小。
 * <pre>   {@code
 *   int cacheSize = 4 * 1024 * 1024; // 4MiB
 *   LruCache<String, Bitmap> bitmapCache = new LruCache<String, Bitmap>(cacheSize) {
 *       protected int sizeOf(String key, Bitmap value) {
 *           return value.getByteCount();
 *       }
 *   }}</pre>
 *
 * <p>This class is thread-safe. Perform multiple cache operations atomically by
 * synchronizing on the cache: <pre>   {@code
 *   synchronized (cache) {
 *     if (cache.get(key) == null) {
 *         cache.put(key, value);
 *     }
 *   }}</pre>
 *
 * <p>This class does not allow null to be used as a key or value. A return
 * value of null from {@link #get}, {@link #put} or {@link #remove} is
 * unambiguous: the key was not in the cache.
 * 不允许key或者value为null
 *  当get(),put(),remove()返回值为null时,key相应的项不在cache中
 */
public class LruCache<K, V> {
    private final LinkedHashMap<K, V> map;  

    /** Size of this cache in units. Not necessarily the number of elements. */
    private int size; //已经存储的大小
    private int maxSize; //规定的最大存储空间

    private int putCount;  //put的次数
    private int createCount;  //create的次数
    private int evictionCount;  //回收的次数
    private int hitCount;  //命中的次数
    private int missCount;  //丢失的次数

    /**
     * @param maxSize for caches that do not override {@link #sizeOf}, this is
     *     the maximum number of entries in the cache. For all other caches,
     *     this is the maximum sum of the sizes of the entries in this cache.
     */
    public LruCache(int maxSize) {
        if (maxSize <= 0) {
            throw new IllegalArgumentException("maxSize <= 0");
        }
        this.maxSize = maxSize;
        this.map = new LinkedHashMap<K, V>(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 to the
     * head of the queue. This returns null if a value is not cached and cannot
     * 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) {
                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.
         * 如果丢失了就试图创建一个item
         */  

        V createdValue = create(key);
        if (createdValue == null) {
            return null;
        }  

        synchronized (this) {
            createCount++;//创建++
            mapValue = map.put(key, createdValue);  

            if (mapValue != null) {
                // There was a conflict so undo that last put
                //如果前面存在oldValue,那么撤销put()
                map.put(key, mapValue);
            } else {
                size += safeSizeOf(key, createdValue);
            }
        }  

        if (mapValue != null) {
            entryRemoved(false, key, createdValue, mapValue);
            return mapValue;
        } else {
            trimToSize(maxSize);
            return createdValue;
        }
    }  

    /**
     * Caches {@code value} for {@code key}. The value is moved to the head of
     * 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);
            previous = map.put(key, value);
            if (previous != null) {  //返回的先前的value值
                size -= safeSizeOf(key, previous);
            }
        }  

        if (previous != null) {
            entryRemoved(false, key, previous, value);
        }  

        trimToSize(maxSize);
        return previous;
    }  

    /**
     * @param maxSize the maximum size of the cache before returning. May be -1
     *     to evict even 0-sized elements.
     *  清空cache空间
     */
    private void trimToSize(int maxSize) {
        while (true) {
            K key;
            V value;
            synchronized (this) {
                if (size < 0 || (map.isEmpty() && size != 0)) {
                    throw new IllegalStateException(getClass().getName()
                            + ".sizeOf() is reporting inconsistent results!");
                }  

                if (size <= maxSize) {
                    break;
                }  

                Map.Entry<K, V> toEvict = map.eldest();
                if (toEvict == null) {
                    break;
                }  

                key = toEvict.getKey();
                value = toEvict.getValue();
                map.remove(key);
                size -= safeSizeOf(key, value);
                evictionCount++;
            }  

            entryRemoved(true, key, value, null);
        }
    }  

    /**
     * Removes the entry for {@code key} if it exists.
     * 删除key相应的cache项,返回相应的value
     * @return the previous value mapped by {@code 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.
     * 当item被回收或者删掉时调用。改方法当value被回收释放存储空间时被remove调用,
     * 或者替换item值时put调用,默认实现什么都没做。
     * <p>The method is called without synchronization: other threads may
     * 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 by a {@link #put} or {@link #remove}.
     * true---为释放空间被删除;false---put或remove导致
     * @param newValue the new value for {@code key}, if it exists. If non-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, V newValue) {}  

    /**
     * Called after a cache miss to compute a value for the corresponding key.
     * Returns the computed value or null if no value can be computed. The
     * default implementation returns null.
     * 当某Item丢失时会调用到,返回计算的相应的value或者null
     * <p>The method is called without synchronization: other threads may
     * access the cache while this method is executing.
     *
     * <p>If a value for {@code key} exists in the cache when this method
     * returns, the created value will be released with {@link #entryRemoved}
     * and discarded. This can occur when multiple threads request the same key
     * at the same time (causing multiple values to be created), or when one
     * thread calls {@link #put} while another is creating a value for the same
     * 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 default implementation returns 1 so that size
     * is the number of entries and max size is the maximum number of entries.
     * 返回用户定义的item的大小,默认返回1代表item的数量,最大size就是最大item值
     * <p>An entry‘s size must not change while it is in the cache.
     */
    protected int sizeOf(K key, V value) {
        return 1;
    }  

    /**
     * Clear the cache, calling {@link #entryRemoved} on each removed entry.
     * 清空cacke
     */
    public final void evictAll() {
        trimToSize(-1); // -1 will evict 0-sized elements
    }  

    /**
     * For caches that do not override {@link #sizeOf}, this returns the number
     * 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 the maximum
     * 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 that was
     * already present in the cache.
     */
    public synchronized final int hitCount() {
        return hitCount;
    }  

    /**
     * Returns the number of times {@link #get} returned null or required a new
     * 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 from least
     * recently accessed to most recently accessed. 返回当前cache的副本,从最近最少访问到最多访问
     */
    public synchronized final Map<K, V> snapshot() {
        return new LinkedHashMap<K, V>(map);
    }  

    @Override public synchronized final String toString() {
        int accesses = hitCount + missCount;
        int hitPercent = accesses != 0 ? (100 * hitCount / accesses) : 0;
        return String.format("LruCache[maxSize=%d,hits=%d,misses=%d,hitRate=%d%%]",
                maxSize, hitCount, missCount, hitPercent);
    }
}  

本文转自:http://blog.csdn.net/linghu_java/article/details/8574102

时间: 2024-10-10 18:22:02

Android提供的LruCache类简介的相关文章

Android提供的LruCache类简介[转载]

转自:here 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

android提供的TextUtils类

对于字符串处理Android为我们提供了一个简单实用的TextUtils类,如果处理比较简单的内容不用去思考正则表达式不妨试试这个在android.text.TextUtils的类,主要的功能如下: 是否为空字符 boolean android.text.TextUtils.isEmpty(CharSequence str)  拼接字符串 String android.text.TextUtils.join(CharSequence delimiter, Object[] tokens) 拆分字

一个使用命令行编译Android项目的工具类

一个使用命令行编译Android项目的工具类 简介 编译apk项目需要使用的几个工具,基本都在sdk中,它们分别是(Windows系统): 1.aapt.exe 资源打包工具 2.android.jar Android编译工具 3.dx.bat dex文件生成工具 4.sdklib.jar 生成apk 5.jarsigner 签名工具 准备 在打包前,需要的环境如下: 1.JDK1.6+ 2.Android SDK 3.上述5个工具的路径 打包过程 1.生成R.java文件 比如: aapt p

Android 网络编程 API笔记 - java.net 包 权限 地址 套接字 相关类 简介

Android 网络编程相关的包 : 9 包, 20 接口, 103 类, 6 枚举, 14异常; -- Java包 : java.net 包 (6接口, 34类, 2枚举, 12异常); -- Android包 : android.net 包 (1接口, 19类, 3枚举, 1异常), android.net.http 包 (6类), android.net.nsd 包 (3接口, 2类), android.net.rtp (4类), android.net.sip 包 (1接口, 9类, 1

android application类简介(一)

每次应用程序运行时,应用程序的application类保持实例化的状态.通过扩展applicaiton类,可以完成以下3项工作: 1.对android运行时广播的应用程序级事件如低低内做出响应. 2.在应用程序组件之间传递对象(全局变量). 3.管理和维护多个应用程序组件使用的资源. 其中,后两项工作通过使用单例类来完成会更好.application会在创建应用程序进程的时候实例化. 下面是扩展Application的示例代码: import android.app.Application; p

19_利用android提供的HanziToPinyin工具类实现汉字与拼接的转换

汉字转换成拼接的效果有很多实现方式,例如pinyin4j是一个流行的Java库,支持中文字符和拼音之间的转换.拼音输出格式可以定制(后面的博客会详细介绍使用方法).但是在android的系统应用联系人中也给我们实现了汉字与拼接转换的方式,接下来我们简单介绍一下android中汉字与拼音的转换. 1.首先到https://github.com/android网站上去下载android提供联系人接口的源码android/platform_packages_providers_contactsprov

Android的基本世界观——系统简介,组件逻辑及其他

前言 作为一个有半年余Android Developing折腾经验的Android Developer(为什么不说"开发经验"呢?因为我仔细想了想,我还没有独立地做出一个完善美观且有使用价值的应用.),要系统地学习安卓平台的基本开发技能,那么第一步,了解并熟识Android的基本世界观,应该就是十分必要的了.以前这方面的知识体系不成系统,比较破碎零散,故借此文稍作整理. 我认为在进入任何一个比较复杂的知识技能体系之前,都需要先用基本世界观来热热身.对于高中物理而言,初中数学物理知识就形

Android 关于使用LruCache缓存你想缓存的数据

又是好久没写博客.. 今天我们来一起学习一下缓存技术,相信大家做开发的时候都知道请求网络数据的重要,但是有一些只用请求一次就过时性的消息比如某些新闻信息,如果我们每次进入新闻界面就从新从网络上获取势必会给用户带来不好的体验,所以我们需要缓存技术来帮我们解决这一问题. 1,LruCache介绍 核心的类是LruCache (此类在android-support-v4的包中提供) .这个类非常适合用来缓存图片,它的主要算法原理是把最近使用的对象用强引用存储在 LinkedHashMap 中,并且把最

第一章 android以及智能手机行业相关简介

第一章 android以及智能手机行业相关简介读后感受&知识累计 最近深刻了解到自己基础知识的不足,变不断的开始阅读很多android相关的知识,希望这些对本人未来的职业发展有很大的帮助.下面的部分知识并不是书中原来的样子,是本人综合了一下,整合的感受和知识,本人写博客并不是为了帮助大家在代码层面解决问题,只是为了方便有向我一样的ce来积累知识,固图片很少,纯文字型的. 一.android简介 1.android的产生 android是有OHA(开放手机联盟)vs 谷歌一切提供的一款软件平台,至