LruCache缓存方法

package android.util;
public class LruCache <K, V>{
    public LruCache(int maxSize){}
    ...
}

LRU是Least Recently Used 近期最少使用算法。内存管理的一种页面置换算法,对于在内存中但又不用的数据块(内存块)叫做LRU,操作系统会根据哪些数据属于LRU而将其移出内存.
明白了LRU,从字面意思就能明白LruCache的作用了。
先看看developer怎么说:
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.
这段说的是它的原理,之后的说的是它的方法,就不写上来了。
LruCache使用强引用hold住制定数量的资源不被回收掉,又按照LRU的规则,把后进来的放进队列的头部,当加入的数据超过指定的size的时候从队尾开始删除。
列一下它所有的方法:

 public final V get(K key) { /* compiled code */ }

    public final V put(K key, V value) { /* compiled code */ }

    public void trimToSize(int maxSize) { /* compiled code */ }

    public final V remove(K key) { /* compiled code */ }

    protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) { /* compiled code */ }

    protected V create(K key) { /* compiled code */ }

    protected int sizeOf(K key, V value) { /* compiled code */ }

    public final void evictAll() { /* compiled code */ }

    public final synchronized int size() { /* compiled code */ }

    public final synchronized int maxSize() { /* compiled code */ }

    public final synchronized int hitCount() { /* compiled code */ }

    public final synchronized int missCount() { /* compiled code */ }

    public final synchronized int createCount() { /* compiled code */ }

    public final synchronized int putCount() { /* compiled code */ }

    public final synchronized int evictionCount() { /* compiled code */ }

    public final synchronized java.util.Map<K,V> snapshot() { /* compiled code */ }

    public final synchronized java.lang.String toString() { /* compiled code */ }
}

典型的数据结构方法,存取计数一类。

private LruCache<Integer, String> mCache;
    int size = 5;
    mCache = new LruCache<Integer,String>(size){
            @Override
            protected int sizeOf(Integer key,String value){
                return 0;
            }
        };
        for(int i=0;i <10;i++) {
            mCache.put(i, "i");
        }
        for(int i=0;i <10;i++) {
            String tempValue = mCache.get(i);
            if(tempValue ==null) {
                mCache.put(i, "i");
            }
        }
        System.out.println(mCache);

因为看到有toString方法,所以想着打印一下,

I/System.out(6418): LruCache[maxSize=5,hits=10,misses=0,hitRate=100%]

打印出来的LruCache包含了最大值maxSize,hits,hitRate,misses命中率的内容。
因为我们put了K,V进去所以读取的时候可以命中,如果没有提前put键值对进去命中率就会反过来。
至此简单的LruCache基本明了。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值