Bitmap内存缓存框架(一)

UniverseImageLoader加载图片首先从内存加载,对于其使用的内存缓存框架可以拿来自己用,也值得去看一下它的实现。

首先实现一个通用的内存框架的接口MemoryCache

/**
 * @描述:cache接口
 * @filename:MemoryCache.java
 * @author:gac
 * @time:2018/6/28 16:03
 */
public interface MemoryCache {
    /**
     * 根据key值存储元素
     * @param key
     * @param value
     * @return
     */
    boolean put(String key,Bitmap value);

    /**
     * 获取元素
     * @param key
     * @return
     */
    Bitmap get(String key);

    /**
     * 删除元素 返回被删除的元素
     * @param key
     * @return
     */
    Bitmap remove(String key);

    /**
     * 获取keys 集合
     * @return
     */
    Collection<String> keys();

    /**
     * 清空缓存
     */
    void clear();
}

提供一个基类BaseMemoryCache

/**
 * @描述:基础memoryCache实现
 * @filename:BaseMemoryCache.java
 * @author:gac
 * @time:2018/6/28 16:07
 */
public abstract class BaseMemoryCache implements MemoryCache {
    //提供弱引用 缓存bitmap 可回收 采用synchornizedMap解决并发问题
    private final Map<String,Reference<Bitmap>> softMap = Collections.synchronizedMap(new HashMap<String, Reference<Bitmap>>());

    /**
     * 存储bitmap
     * @param key
     * @param value
     * @return
     */
    @Override
    public boolean put(String key, Bitmap value) {
        softMap.put(key,createReference(value));
        return true;
    }

    /**
     * 获取bitmap
     * @param key
     * @return
     */
    @Override
    public Bitmap get(String key) {
        Bitmap result = null;
        Reference<Bitmap> reference = softMap.get(key);
        if(reference != null){
            result = reference.get();
        }
        return result;
    }

    @Override
    public Bitmap remove(String key) {
        Reference<Bitmap> bmpRef = softMap.remove(key);
        return bmpRef == null ? null : bmpRef.get();
    }

    /**
     * 获取键的集合 当有线程对softMap对象执行该操作时候 只有该线程可以操作该对象 不允许其它线程 调用put remove等修改方法
     * @return
     */
    @Override
    public Collection<String> keys() {
        synchronized (softMap){
            return new HashSet<String>(softMap.keySet());
        }
    }

    /**
     * 清空内存缓存
     */
    @Override
    public void clear() {
        softMap.clear();
    }

    /**
     * 创建Bitmap 弱引用对象
     * @param value
     * @return
     */
    protected abstract Reference<Bitmap> createReference(Bitmap value);

}

下面介绍几种缓存策略:第一种根据使用频率去对bitmap对象进行删除,使用次数最少的优先被删除
UsingFreqLimitedMemoryCache

/**
 * @描述:限定大小存储bitmap 缓存达到限制 根据使用频率进行删除
 * @filename:UsingFreqLimitedMemoryCache.java
 * @author:gac
 * @time:2018/6/28 17:53
 */
public class UsingFreqLimitedMemoryCache extends LimitedMemoryCache{
    /**
     * 记录每个bitmap 的使用次数 强引用bitmap bitmap删除后 softMap中会自己被内存回收
     */
    private final Map<Bitmap,Integer> usingCounts = Collections.synchronizedMap(new HashMap<Bitmap,Integer>());

    public UsingFreqLimitedMemoryCache(int sizeLimit){
        super(sizeLimit);
    }

    @Override
    public boolean put(String key, Bitmap value) {
        if(super.put(key,value)){//如果保存成功 则设置bitmap使用次数是0 只要更新了对象
            usingCounts.put(value,0);
            return true;
        }else{
            return false;
        }
    }

    @Override
    public Bitmap get(String key) {
        Bitmap value = super.get(key);
        if(value != null){//需要判空 弱引用随时可能被回收
            Integer usageCount = usingCounts.get(value);
            if(usageCount != null){//put 方法可能会失败 需要判空
                usingCounts.put(value,usageCount+1);
            }
        }
        return value;
    }

    @Override
    public Bitmap remove(String key) {
        Bitmap value = super.get(key);
        if(value != null){
            usingCounts.remove(value);//删除元素 删除计数器的强引用
        }
        return super.remove(key);
    }

    @Override
    public void clear() {
        usingCounts.clear();
        super.clear();
    }

    @Override
    protected int getSize(Bitmap value) {
        return value.getRowBytes()*value.getHeight();
    }

    @Override
    protected Bitmap removeNext() {
        Integer minUsageCount = null;//最少使用次数记录器
        Bitmap leastUsedValue = null;//最少使用次数bitmap记录器
        Set<Map.Entry<Bitmap,Integer>> entries = usingCounts.entrySet();
        synchronized (usingCounts){//对usingCounts进行查找操作 时候 不允许对usingCounts进行其它操作
            for(Map.Entry<Bitmap,Integer> entry : entries){
                if(leastUsedValue == null){//第一次执行的时候 初始化 minUssageCount leastUsedValue为第一个值
                    leastUsedValue = entry.getKey();
                    minUsageCount = entry.getValue();
                }else{
                    Integer lastValueUsage = entry.getValue();//获取下一个元素的 使用次数
                    if(lastValueUsage < minUsageCount){//如果下一个元素使用次数更新 指针偏移
                        minUsageCount = lastValueUsage;
                        leastUsedValue = entry.getKey();
                    }
                }
            }//找到使用次数最少的bitmap
        }
        usingCounts.remove(leastUsedValue);
        return leastUsedValue;
    }

    @Override
    protected Reference<Bitmap> createReference(Bitmap value) {
        return new WeakReference<Bitmap>(value);
    }
}

限制内存大小,超过最大内存缓存的时候,增加元素就会清除元素直到内存达到限制要求LimitedMemoryCache

/**
 * @描述:限制内存大小的bitmap缓存基础类
 * @filename:LimitedMemoryCache.java
 * @author:gac
 * @time:2018/6/28 16:44
 */
public abstract class LimitedMemoryCache extends BaseMemoryCache {
    private static final int MAX_NORMAL_SIZE_IN_MB = 16;//默认最大内存缓存 M单位
    private static final int MAX_NORMAL_CACHE_SIZE = MAX_NORMAL_SIZE_IN_MB*1024*1024;//最大缓存字节数
    private final int sizeLimit;//用户设置的缓存限制大小
    private final AtomicInteger cacheSize;//当前内存缓存数量
    /*强引用对象存储 缓存的bitmap集合,添加则添加集合的尾部,如果超过限定的缓存 则会删除集合第一个元素,一直
    * 达到内存到达限定大小,即使删除了内存的缓存 BaseMemoryCache softMap依然存在Bitmap的弱引用
    * 但是可以被gc 在任何时候回收掉
    * */
    private final List<Bitmap> hardCache = Collections.synchronizedList(new LinkedList<Bitmap>());
    public LimitedMemoryCache(int sizeLimit){
        this.sizeLimit = sizeLimit;
        cacheSize = new AtomicInteger();
        if(sizeLimit > MAX_NORMAL_CACHE_SIZE){
            Log.e("cache","you set too large memory cache size(more than 16MB");
        }
    }

    @Override
    public boolean put(String key, Bitmap value) {
        boolean putSuccessfully = false;
        int valueSize = getSize(value);//计算存储的bitmap的大小
        int sizeLimit = getSizeLimit();//获取用户设置的缓存大小
        int curCacheSize = cacheSize.get();//当前已经占用的缓存大小
        if(valueSize < sizeLimit){//设置的bitmap小于设置的缓存
            while (curCacheSize + valueSize > sizeLimit){//如果缓存超出了则调用removeNext删除对象
                Bitmap removedValue = removeNext();//获取需要删除的bitmap
                if(hardCache.remove(removedValue)){//删除 list 强引用 softMap中还存在 等待gc 自动回收
                    curCacheSize = cacheSize.addAndGet(-getSize(removedValue));
                }
                hardCache.add(value);//添加list 强引用
                cacheSize.addAndGet(valueSize);//更新当前缓存数
                putSuccessfully = true;
            }

        }
        super.put(key, value);//add bitmap to softCache
        return putSuccessfully;
    }

    @Override
    public Bitmap remove(String key) {
        Bitmap value = super.get(key);
        if(value != null){
            if(hardCache.remove(value)){//删除强引用
                cacheSize.addAndGet(-getSize(value));//更新当前缓存值
            }
        }
        return super.remove(key);//删除弱引用
    }

    /**
     * 清空缓存
     */
    @Override
    public void clear() {
        hardCache.clear();
        cacheSize.set(0);
        super.clear();
    }

    /**
     * 获取bitmap大小的计算方法
     * @param value
     * @return
     */
    protected abstract int getSize(Bitmap value);

    /**
     * 删除缓存的bitmap算法 核心
     * @return
     */
    protected abstract Bitmap removeNext();

    /**
     * 获取用户设置的默认缓存大小
     * @return
     */
    protected int getSizeLimit(){
        return sizeLimit;
    }

根据元素访问次序进行删除,很少被访问的元素优先被清理,LruMemoryCache

/**
 * @描述:根据元素的访问顺序进行移除元素
 * 经常被访问的不会删除,很少访问的会被优先删除
 * @filename:LruMemoryCache.java
 * @author:gac
 * @time:2018/6/29 9:10
 */
public class LruMemoryCache implements MemoryCache{
    //LinkedHashMap 每一次调用put方法 或者 get方法 都会将访问的元素放在链表尾部
    //也就是 访问的元素都是最长没有被访问过的元素
    private final LinkedHashMap<String,Bitmap> map;
    private final int maxSize;//最大内存缓存数量
    private int size;//记录当前已经缓存的内存数量

    //设置最大内存缓存 初始化map
    public LruMemoryCache(int maxSize){
        if(maxSize <= 0){
            throw new IllegalArgumentException("maxSize <= 0");
        }
        this.maxSize = maxSize;
        this.map = new LinkedHashMap<String,Bitmap>(0,0.75f,true);
    }
    @Override
    public boolean put(String key, Bitmap value) {
        if(key == null || value == null){
            throw new NullPointerException("key == null || value == null ");
        }
        //同步代码块 对LruMemoryCache加锁 如果执行这里 不允许进行其它操作,防止改变当前size的值,造成不准确
        synchronized (this){
            size+=sizeOf(key,value);
            Bitmap previous = map.put(key,value);//获取先前保存的bitmap
            if(previous != null){
                size-= sizeOf(key,value);//减去被更新的bitmap的容量
            }
        }
        trimToSize(maxSize);
        return true;
    }
    //对内存进行清理
    private void trimToSize(int maxSize){
        while (true){
            String key;
            Bitmap value;
            /**
             * 同步代码块,清理内存的时候,不允许其它类对LurMemoryCache进行操作
             */
            synchronized (this){
                if(size < 0 || (map.isEmpty() && size != 0)){
                    throw new IllegalStateException(getClass().getSimpleName()+".sizeOf() is reporting inconsistent results!");
                }
                if(size <= maxSize || map.isEmpty()){
                    break;
                }
                Map.Entry<String,Bitmap> toEvict = map.entrySet().iterator().next();//不断获取btimap下一个元素(很少访问的元素最先获取)
                if(toEvict == null){
                    break;
                }
                key = toEvict.getKey();
                value = toEvict.getValue();
                map.remove(value);//删除value
                size-=sizeOf(key,value);//更新当前缓存
            }
        }
    }
    @Override
    public Bitmap get(String key) {
        if(key == null){
            throw new NullPointerException("key == null");
        }
        //同步LruMemoryCache对象 如果执行这里 不允许对map进行其它操作
        synchronized (this){
            return map.get(key);
        }


    }

    @Override
    public Bitmap remove(String key) {
        if(key == null){
            throw new NullPointerException("key == null");
        }
        synchronized (this){//对map进行更新操作 同步代码块 防止错误发生
            Bitmap previous = map.remove(key);//获取被删除的元素
            if(previous != null){
                size -= sizeOf(key,previous);//更新当前内存
            }
            return previous;
        }
    }

    @Override
    public Collection<String> keys() {
        //同步代码块  防止keys 由于其他线程 防止变化
        synchronized (this){
            return new HashSet<String>(map.keySet());
        }
    }


    /**
     * 记录bitmap大小
     * @param key
     * @param value
     * @return
     */
    private int sizeOf(String key, Bitmap value) {
        return value.getRowBytes() * value.getHeight();
    }
    @Override
    public void clear() {
        trimToSize(-1);
    }

    @Override
    public synchronized final String toString() {
        return String.format("LruCache[maxSize=%d]", maxSize);
    }
}

对内存大小进行限制,根据访问顺序去清理内存,很少访问的元素优先被清理,LRULimitedMemoryCache

/**
 * @描述:对内存大小进行了限制 最大16M
 * LruMemoryCache可以手动设置最大内存
 * @filename:LRULimitedMemoryCache.java
 * @author:gac
 * @time:2018/6/29 9:55
 */
public class LRULimitedMemoryCache extends LimitedMemoryCache {
    private static final int INITIAL_CAPACITY = 10;//初始化LinkHashMap容器大小
    private static final float LOAD_FACTOR = 1.1f;//LinkedHashMap 容器重置时候增大的比例
    //lruCache 强引用保存元素 使用LinkedHashMap保证 很少访问的元素被优先删除
    private final Map<String,Bitmap> lruCache = Collections.synchronizedMap(
            new LinkedHashMap<String, Bitmap>(INITIAL_CAPACITY,LOAD_FACTOR)
    );
    public LRULimitedMemoryCache(int sizeLimit) {
        super(sizeLimit);
    }

    @Override
    public boolean put(String key, Bitmap value) {
        if(super.put(key,value)){
            lruCache.put(key,value);
            return true;
        }else{
            return false;
        }
    }

    @Override
    public Bitmap remove(String key) {
        lruCache.remove(key);
        return super.remove(key);
    }

    @Override
    public void clear() {
        lruCache.clear();
        super.clear();
    }

    @Override
    protected Reference<Bitmap> createReference(Bitmap value) {
        return new WeakReference<Bitmap>(value);
    }

    @Override
    protected int getSize(Bitmap value) {
        return value.getRowBytes()*value.getHeight();
    }

    @Override
    protected Bitmap removeNext() {
        Bitmap mostLoginUsedValue = null;//最长没有被使用过的元素
        //同步代码块lruCache 防止删除元素的时候其它线程进行更新操作
        synchronized (lruCache){
            Iterator<Map.Entry<String,Bitmap>> it = lruCache.entrySet().iterator();
            if(it.hasNext()){
                Map.Entry<String,Bitmap> entry = it.next();
                mostLoginUsedValue = entry.getValue();
                it.remove();
            }
        }
        return mostLoginUsedValue;
    }
}

设置保存时间,根据保存时间有没有过期去清理元素LimitedAgeMemoryCache

/**
 * @描述:根据设置保存元素的时间 去清理内存
 * @filename:LimitedAgeMemoryCache.java
 * @author:gac
 * @time:2018/6/29 10:09
 */
public class LimitedAgeMemoryCache implements MemoryCache{
    private final MemoryCache cache;//设置的底层缓存原理 可以是任何一种实现MemoryCache接口的方案
    private final long maxAge;//元素需要保存的时间 单位秒
    //存储bitmap的key值和保存元素的时间
    private final Map<String,Long> loadingDates = Collections.synchronizedMap(new HashMap<String, Long>());
    //构造方法 初始化统一的保存时间 和底层缓存原理
    public LimitedAgeMemoryCache(MemoryCache cache,long maxAge){
        this.cache = cache;
        this.maxAge = maxAge*1000;//转换为毫秒
    }
    @Override
    public boolean put(String key, Bitmap value) {
        boolean putSuccessfully = cache.put(key,value);
        if(putSuccessfully){
            loadingDates.put(key,System.currentTimeMillis());//保存元素的key 和当前时间戳
        }
        return putSuccessfully;
    }

    @Override
    public Bitmap get(String key) {
        Long loadingDate = loadingDates.get(key);
        //如果元素保存的时长 大于maxAge 则删除元素
        if(loadingDate != null && System.currentTimeMillis() -loadingDate > maxAge){
            cache.remove(key);
            loadingDates.remove(key);
        }
        return cache.get(key);//获取元素
    }

    @Override
    public Bitmap remove(String key) {
        loadingDates.remove(key);
        return cache.remove(key);
    }

    @Override
    public Collection<String> keys() {
        return cache.keys();
    }

    @Override
    public void clear() {
        cache.clear();
        loadingDates.clear();
    }
}
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值