Android缓存 LruCache

LruCache

LruCache是Android3.1提供的缓存类,并且在v4包提供了该类。LruCache是一个泛型类,它内部提供了LinkedHashMap作为存储工具,被缓存的对象会添加到LinkedHashMap中。而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);
}

创建LruCache对象时,它内部做的工作如下:

  1. 记录下制定的最大容量maxSize。
  2. 创建一个初始容量为0的LinkedHashMap,用来保存对象

所以,在创建LruCache对象时,我们需要指定一个最大容量值maxSize,它可以是具体数值,也可以是内存空间,与它对应的是sizeOf方法:

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

如果我们想以数量的方式来控制缓存,可以看到,默认的sizeOf方法返回值为1,也就是说每次添加一条数据,它所占用的空间为1,直到添加的内容数量达到maxSize,这时候再添加数据,系统就会挑选出使用频率最低的值,将他们移除。

如果以内存空间作为缓存限制,需要重写size,返回对象所占用的空间大小:

int maxMemory = (int) (Runtime.getRuntime().maxMemory())/1024;//获取可用内存,转换为单位KB
int maxCache = maxMemory/10;//缓存大小为可用内存的1/10
LruCache mMemoryCache = new LruCache<String,Bitmap>(maxCache){
  @Override//重写sizeOf方法,返回每条数据占用的内存
  protected int sizeOf(String key, Bitmap value) {
      return value.getRowBytes()*value.getHeight() / 1024;
      //return value.getByteCount() / 1024;
  }
};
  • 读取内容

读取内容对应的是get方法,源码如下:

public final V get(K key) {
    if (key == null) {     //如果key为null,直接抛出异常
        throw new NullPointerException("key == null");
    }

    V mapValue;
    synchronized (this) {
        mapValue = map.get(key);  //读取key对应的值
        if (mapValue != null) {
            hitCount++;
            return mapValue;     //如果获取到内容,返回
        }
        missCount++;   //如果未读到内容,missCount计数增加,继续向下执行
    }

    /*尝试创建value,可能会消耗一定的时间,当创建完成时,map可能已经发生变化
      如果此时发现创建时使用的key已经存在,导致冲突,丢弃掉create创建的值
     * 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.
     */
    //如果未获取到value,调用create方法,尝试创建对象
    //create方法默认返回null,可以覆写该方法,决定获取不到值时的添加方法
    V createdValue = create(key);
    if (createdValue == null) {
        return null;
    }
    //以下部分为创建之后对map的修改动作,包括存放对象,调整size等。
    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;
    }
}

get方法尝试根据传入的key来读取内容,如果读取不到,可以选择是否创建一个对象,如果选择创建对象,需要我们覆写create方法来返回要创建的对象,使用也很简单

  • 存储内容

存储内容使用的是put方法:

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

在存放内容的时候,可以看到是怎样控制缓存size的:存放内容之后会将执行size += safeSizeOf(key, value);,safeSizeOf的默认实现就是sizeOf方法。 每存放一个对象,就会将size增加对应的值。如果存放的key已经存在数据,那么size不变。

同时还提供了一个entryRemoved方法,该方法在数据被移除时(调用remove移除,新值覆盖,超出缓存被删除)调用,默认实现为空。

在put的最后则是调用了trimToSize,这是控制缓存大小的方法,每当有新的数据存入时,该方法都会被调用。当前size超出缓存最大值之后,会通过此方法删除最近最少使用的数据。

除了正常的存储,读取之外,LruCache还提供了一个一次性读取全部缓存对象的方法:

public synchronized final Map<K, V> snapshot() {
    return new LinkedHashMap<K, V>(map);
}

猜你喜欢

转载自blog.csdn.net/wxpqqa/article/details/80669716