LruCache使用以及源码分析

本文详细介绍Android中的LRUCache使用方法及源码分析,包括构造方法、核心方法trimToSize()等,并介绍了LinkedHashMap的使用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LruCache使用以及源码分析

引言 :  Android开发中我们或多或少都需要用到的图片框架,不同的框架内部都有自己不同的缓存策略,Android原生谷歌提供了一个缓存类LruCache<K, V>,今天说一下具体的用法,然后顺便看一下内部源码的实现,也算是一种学习

在看源码之前首先大致了解一下Linkedhashmap这个类,具体学习以及源码分析放在后续的文章中,Linkedhashmap维护了一个双向链表,LinkedHashMap保证了元素迭代的顺序,但是会牺牲掉一定的性能

使用方法

首先介绍具体的使用,使用没有什么特别复杂的设置,只需要根据实际情况重写sizeOf(),entryRemoved(),create().

        //举个栗子^_^
        final int MAX_SIZE = 1024 * 1024 * 10;//10 M
        LruCache<String, Bitmap> lruCache = new LruCache<String, Bitmap>
        (MAX_SIZE) {
            @Override
            protected int sizeOf(String key, Bitmap value) {
                //计算添加数据的大小
                return value.getByteCount();
            }

            @Override
            protected void entryRemoved(boolean evicted, String key,
            Bitmap oldValue, Bitmap newValue) {
                //处理被删除的数据
                super.entryRemoved(evicted, key, oldValue, newValue);
            }

            @Override
            protected Bitmap create(String key) {
                //用于get的时候如果获取不到值,自己根据自己的方法创建value
                return super.create(key);
            }
        };
       synchronized (cache) {
           if (cache.get(key) == null) {
               cache.put(key, value);
       }}

构造方法

看一下构造方法,构造方法比较简单,首先是对缓存值的大小进行赋值,然后创建一个LinkedHashMap,后续的所有操作都是围绕这个类展开的

    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);
    }

trimToSize( )

重要的方法,该方法是起到口控制缓存容量大小的关键方法, 核心方法,具体来看下面的源码

    //maxSize表示用户设定的缓存容量大小
    public 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;
                }
                //返回head
                Map.Entry<K, V> toEvict = map.eldest();
                if (toEvict == null) {
                    break;
                }

                key = toEvict.getKey();
                value = toEvict.getValue();
                map.remove(key);
                //计算要移除值得的大小,修改size
                size -= safeSizeOf(key, value);
                evictionCount++;
            }
            //将移除的值返回
            entryRemoved(true, key, value, null);
        }
    }

put( )

    public final V put(K key, V value) {
        //对key,value进行校验
        if (key == null || value == null) {
            throw new NullPointerException("key == null || value == null");
        }

        V previous;
        synchronized (this) {
            putCount++;
            //对计算要加入的value的大小,这个值就最终调用的是我们重写的 sizeOf()方法
            size += safeSizeOf(key, value);
            //将键值对加入集合中,同时判断是否有数据返回,如果有数据(该数据为原先的key中返回的value)返回就
            //计算大小,并且修改size的值
            previous = map.put(key, value);
            if (previous != null) {
                size -= safeSizeOf(key, previous);
            }
        }
        //返回原先要被移除的值,可以自重写的entryRemoved()方法中获取该值,进行相关操作
        if (previous != null) {
            entryRemoved(false, key, previous, value);
        }
        //修改size大小,是集合中所有的size值低于设定的最大值
        trimToSize(maxSize);
        return previous;
    private int safeSizeOf(K key, V value) {
        int result = sizeOf(key, value);
        if (result < 0) {
            throw new IllegalStateException("Negative size: " + key + "=" + value);
        }
        return result;
    }

get( )

基本思路跟put()一样,注意源码中英文注释

    public final V get(K key) {
        //非空校验
        if (key == null) {
            throw new NullPointerException("key == null");
        }
        //如果该key有value,那么直接返回value
        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.
         */
        //根据该key用户选择是否创建value
        V createdValue = create(key);
        if (createdValue == null) {
            return null;
        }

        synchronized (this) {
            createCount++;
            mapValue = map.put(key, createdValue);
            //按官方介绍,create()创建是有延迟的,说白了就是异步的,假设存在这这种情况,当你调用根据某个key调用get()
            //方法的时候,这时候如果有延迟create()方法还没有创建出来该值,但是用该key调用了put()方法,所以此时get()
            //方法获取的值应该为最新的值
            if (mapValue != null) 
                // There was a conflict so undo that last put
                map.put(key, mapValue);
            } else {
                size += safeSizeOf(key, createdValue);
            }
        }
        //修改size
        if (mapValue != null) {
            entryRemoved(false, key, createdValue, mapValue);
            return mapValue;
        } else {
            trimToSize(maxSize);
            return createdValue;
        }
    }

remove( )

    public final V remove(K key) {
        if (key == null) {
            throw new NullPointerException("key == null");
        }
        //修改size大小
        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;
    }

remove( )

    public void resize(int maxSize) {
        if (maxSize <= 0) {
            throw new IllegalArgumentException("maxSize <= 0");
        }

        synchronized (this) {
            this.maxSize = maxSize;
        }
        trimToSize(maxSize);
    }

总结

开心的总结时刻,LruCache算发主要是用作内存缓存,当然了实际情况还是需要结合磁盘缓存来使用的,要理解该算法只需要记住两点就可以了,一个是LinkedHashMap的使用以及特性,另一个是trimToSize( ) 方法,只要记住这两方面,理解起来就没有什么问题了,当然了最后还是希望如果发现什么错误欢迎私信或留言指正

邮    箱: bj_email@yeah.net

github: https://github.com/ASCN-BJ

内容概要:文章基于4A架构(业务架构、应用架构、数据架构、技术架构),对SAP的成本中心和利润中心进行了详细对比分析。业务架构上,成本中心是成本控制的责任单元,负责成本归集与控制,而利润中心是利润创造的独立实体,负责收入、成本和利润的核算。应用架构方面,两者都依托于SAP的CO模块,但功能有所区分,如成本中心侧重于成本要素归集和预算管理,利润中心则关注内部交易核算和获利能力分析。数据架构中,成本中心与利润中心存在多对一的关系,交易数据通过成本归集、分摊和利润计算流程联动。技术架构依赖SAP S/4HANA的内存计算和ABAP技术,支持实时核算与跨系统集成。总结来看,成本中心和利润中心在4A架构下相互关联,共同为企业提供精细化管理和决策支持。 适合人群:从事企业财务管理、成本控制或利润核算的专业人员,以及对SAP系统有一定了解的企业信息化管理人员。 使用场景及目标:①帮助企业理解成本中心和利润中心在4A架构下的运作机制;②指导企业在实施SAP系统时合理配置成本中心和利润中心,优化业务流程;③提升企业对成本和利润的精细化管理水平,支持业务决策。 其他说明:文章不仅阐述了理论概念,还提供了具体的应用场景和技术实现方式,有助于读者全面理解并应用于实际工作中。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值