【Java源码分析】Android-LruCache源码分析

内部实现是LinkedHashMap,保持有限数量的值得强引用,值被访问之后就被移动到队列的首部。当队列满了之后,尾部的值会被移除以便于GC回收

类的定义

public class LruCache<K, V> {}
  1. 如果被缓存的值所拥有的职员需要被显式的释放,重载entryRemoved()方法
  2. 默认情况下size方法返回的是条目数,如果需要返回缓存大小,可以重载sizeOf()
  3. 线程安全的类
  4. 不允许NULL的key,因此get put remove返回null的时候是没有二义性的

构造方法

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,如果没有重载sizeOf()那么maxSize是最大条目数,如果重载了,就是用于重载所用单位

取值方法

public final V get(K key) {
    if (key == null) {
        throw new NullPointerException("key == null");
    }

    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.
     */

    V createdValue = create(key);
    if (createdValue == null) {
        return null;
    }

    synchronized (this) {
        createCount++;
        mapValue = map.put(key, createdValue);

        if (mapValue != null) {
            // There was a conflict so undo that last put
            map.put(key, mapValue);
        } else {
            size += safeSizeOf(key, createdValue);
        }
    }

    if (mapValue != null) {
        entryRemoved(false, key, createdValue, mapValue);
        return mapValue;
    } else {
        trimToSize(maxSize);
        return createdValue;
    }
}

如果对应的key存在于缓存或者可以被创建,那么返回key对应的value。否则返回null.
如果在创建过程中出现了值得冲突,那么就丢弃当前创建的value,保留之前的。

存值方法

public final V put(K key, V value) {
    if (key == null || value == null) {
        throw new NullPointerException("key == null || value == null");
    }

    V previous;
    synchronized (this) {
        putCount++;
        size += safeSizeOf(key, value);
        previous = map.put(key, value);
        if (previous != null) {
            size -= safeSizeOf(key, previous);
        }
    }

    if (previous != null) {
        entryRemoved(false, key, previous, value);
    }

    trimToSize(maxSize);
    return previous;
}

将当前的键值对存入Map,并把当前键值对移到队列最前方,返回该key之前映射的值

protected void entryRemoved(boolean evicted, K key, V oldValue, V newValue) {}

键值对被移除时调用,默认是空实现。方法是没有实现同步的,所以在执行时可能被其他线程访问。如果第一个参数是true,就代表是移除以空出空间。如果是false代表是被put或者remove调用。最后一个参数是key对应的新值,如果非空,就说明是被put调用,如果为空,说明是被eviction或者remove

移除最久的键值对

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

            Map.Entry<K, V> toEvict = map.eldest();
            if (toEvict == null) {
                break;
            }

            key = toEvict.getKey();
            value = toEvict.getValue();
            map.remove(key);
            size -= safeSizeOf(key, value);
            evictionCount++;
        }

        entryRemoved(true, key, value, null);
    }
}

移除存在最久的键值对,保证缓存容量在指定容量之内,参数就是缓存阈值。

删除操作

public final V remove(K key) {
    if (key == null) {
        throw new NullPointerException("key == null");
    }

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

删除key所映射的之前的值,返回值是key先前的映射值

缓存未命中时计算给定key的相关值时被调用的方法,在get中被使用(当get的时候当前key没有对应的键值对,就需要调用create()创建)这个方法需要和get结合来看

protected V create(K key) {
    return null;
}

求大小

private int safeSizeOf(K key, V value) {
    int result = sizeOf(key, value);
    if (result < 0) {
        throw new IllegalStateException("Negative size: " + key + "=" + value);
    }
    return result;
}

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

返回给定参数键值对应实体的大小,该大小是用户定义的单位大小比如个数或者KB。默认返回1代表个数

清空缓存

public final void evictAll() {
    trimToSize(-1); // -1 will evict 0-sized elements
}

对每一个entry调用entryRemoved

获取缓存大小

public synchronized final int size() {
    return size;
}

对于没有覆写sizeOf()的时候返回的是缓存中实体的最大个数,如果覆写了sizeOf()返回的是所有实体大小之和的最大值

缓存命中数

public synchronized final int hitCount() {
    return hitCount;
}

public synchronized final int missCount() {
    return missCount;
}

get方法命中次数和未命中数

返回快照

//  ordered from least recently accessed to most recently accessed.
public synchronized final Map<K, V> snapshot() {
    return new LinkedHashMap<K, V>(map);
}

返回当前缓存的一个副本

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值