使用LruCache:缓存是否分配给LruCache实例?

时间:2019-04-07 23:56:22

标签: android caching android-lru-cache

我可能对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

据我了解,缓存将一直存储,直到用户将其删除(手动删除或卸载应用程序),或者在缓存超过允许空间时由系统清除。我想念什么?

3 个答案:

答案 0 :(得分:2)

LruCache对象仅将对对象的引用存储在内存中。一旦丢失对LruCache的引用,LruCache对象和该缓存中的所有对象都会被垃圾回收。没有任何内容存储到磁盘。

答案 1 :(得分:0)

是的。我只是在这里分享我的困惑,以防万一也有人。

最初,由于使用LruCache推荐this guide (Caching Bitmaps),给我留下了LruCache是​​访问应用程序缓存的接口的印象,但就像@CommonsWare提到的那样,它没有I / O-它只是使用LRU策略保存内存的实用程序类。要访问应用程序的缓存,您需要使用Context.getCacheDir()good explanation here。就我而言,我最终只使用了一个LruCache,因为大多数时候我已经在运行一个服务,该应用程序不会在每次关闭时被杀死。

答案 2 :(得分:-1)

log(CacheInterface().getBitmap("key1")) //null

等于

val instance2 = CacheInterface()
log(instance2 .getBitmap("key1"))

instance1!= instance2

更改为Singleton

object CacheInterface{
...
}

使用

CacheInterface.storeBitmap("key1",bitmap)
CacheInterface.getBitmap("key1")
相关问题