LruCache

作者: 大盗海洲 | 来源:发表于2019-04-23 16:22 被阅读0次
LruCache的使用
//获取系统分配给每个应用程序的最大内存
int maxMemory=(int)(Runtime.getRuntime().maxMemory()/1024);
int cacheSize=maxMemory/8; 
private LruCache<String, Bitmap> mMemoryCache;
//给LruCache分配1/8 
mMemoryCache = new LruCache<String, Bitmap>(mCacheSize){  
    //重写该方法,来测量Bitmap的大小  
    @Override  
    protected int sizeOf(String key, Bitmap value) {  
        return value.getRowBytes() * value.getHeight()/1024;  
    }  
};

LruCache部分源码解析
    /**
     * @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);
    }

LruCache 利用 LinkedHashMap 的一个特性(accessOrder=true 基于访问顺序)再加上对 LinkedHashMap 的数据操作上锁实现的缓存策略。
LruCache 的数据缓存是内存中的。

首先设置了内部 LinkedHashMap 构造参数 accessOrder=true, 实现了数据排序按照访问顺序。
LruCache类在调用get(K key) 方法时,都会调用LinkedHashMap.get(Object key) 。
如上述设置了 accessOrder=true 后,调用LinkedHashMap.get(Object key) 都会通过LinkedHashMap的afterNodeAccess()方法将数据移到队尾。
由于最新访问的数据在尾部,在 put 和 trimToSize 的方法执行下,如果发生数据移除,会优先移除掉头部数据

相关文章

网友评论

      本文标题:LruCache

      本文链接:https://www.haomeiwen.com/subject/aycugqtx.html