LruCache源码分析及思考

本文深入解析LRuCache中的关键代码,详细解释如何通过LinkedHashMap实现LRU算法,确保内存使用合理,避免溢出。同时,阐述每次put操作时的安全检查机制,以及如何在get操作中实现节点的移动,保持缓存高效运行。

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

先来看看给我印象深刻的Lrucache中的关键代码。

//得到图片大小需覆写的方法

 protected int sizeOf(K key, V value) {
        return 1;

//返回图片也就是value的占用内存的大小
    }

// 第三个是关键性参数,true的话,map在get操作的时候,如果返回不为空的话,会将当前节点移到最前端

this.map = new LinkedHashMap<K, V>(0, 0.75f, true);


LinkedHashMap源码:

 if (accessOrder)
                makeTail((LinkedEntry<K, V>) e);
            return e.value;
            /**
     * Relinks the given entry to the tail of the list. Under access ordering,
     * this method is invoked whenever the value of a  pre-existing entry is
     * read by Map.get or modified by Map.put.
     */
    private void makeTail(LinkedEntry<K, V> e) {
        // Unlink e
        e.prv.nxt = e.nxt;
        e.nxt.prv = e.prv;


        // Relink e as tail
        LinkedEntry<K, V> header = this.header;
        LinkedEntry<K, V> oldTail = header.prv;
        e.nxt = header;
        e.prv = oldTail;
        oldTail.nxt = header.prv = e;
        modCount++;
    }

一直以来困惑我的问题在于Lrucache在get的时候,返回不为空的时候,是怎么实现的让当前节点移动到链表map的最前端,今天看源码的时候得到了解答。

然后Lrucache每次put操作时都会安全检查一下。当超出时,则:

  Map.Entry<K, V> toEvict = map.entrySet().iterator().next();
                key = toEvict.getKey();
                value = toEvict.getValue();
                map.remove(key);
                size -= safeSizeOf(key, value);

差不多了,这就是我对LruCache是怎么实现LRU算法,并且能保证内存不溢出的理解!!!


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值