首页 > 解决方案 > 使用 LruCache:缓存是否附加到 LruCache 实例?

问题描述

我可能只是对应该如何LruCache工作感到困惑,但它是否不允许从一个实例访问保存在另一个实例上的对象?当然不是这样,否则它有点违背了拥有缓存的目的。

例子:

class CacheInterface {

    private val lruCache: LruCache<String, Bitmap>

    init {
        val maxMemory = (Runtime.getRuntime().maxMemory() / 1024).toInt()
        // Use 1/8th of the available memory for this memory cache.
        val cacheSize = maxMemory / 8
        lruCache = object : LruCache<String, Bitmap>(cacheSize) {
            override fun sizeOf(key: String, value: Bitmap): Int {
                return value.byteCount / 1024
            }
        }
    }

    fun getBitmap(key: String): Bitmap? {
        return lruCache.get(key)
    }

    fun storeBitmap(key: String, bitmap: Bitmap) {
        lruCache.put(key, bitmap)
        Utils.log(lruCache.get(key))
    }

}
val bitmap = getBitmal()
val instance1 = CacheInterface()
instance1.storeBitmap("key1", bitmap)
log(instance1.getBitmap("key1")) //android.graphics.Bitmap@6854e91
log(CacheInterface().getBitmap("key1")) //null

据我了解,缓存会一直存储到用户删除(手动或卸载应用程序),或者当超过允许的空间时被系统清除。我错过了什么?

标签: androidcachingandroid-lru-cache

解决方案


LruCache对象只是在内存中存储对对象的引用。一旦失去对 的引用,该缓存中LruCacheLruCache对象和所有对象都会被垃圾回收。磁盘上没有存储任何内容。


推荐阅读