【问题标题】:Using LruCache: Is cache attatched to a LruCache instance?使用 LruCache:缓存是否附加到 LruCache 实例?
【发布时间】:2019-08-29 02:06:13
【问题描述】:

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

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

【问题讨论】:

    标签: android caching android-lru-cache


    【解决方案1】:

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

    【讨论】:

    • 那么在用户杀死你的应用程序、进程被杀死并且任何静态引用都被垃圾回收后,你如何访问你的应用程序的缓存?
    • >磁盘上没有存储任何内容。当我杀死手机上的应用程序时,缓存不会被清除,甚至重新启动系统
    • @JohnSardinha:那么您的测试可能有问题。 Here is the source code。你会发现里面没有磁盘I/O。
    • 对于意味着在进程之间持久存在的缓存,LruCache 不是使用正确的接口吗? LruCache 只是为了缓存要在同一个“会话”中访问的数据吗?
    • @JohnSardinha - 没错。它只是一个内存缓存。
    【解决方案2】:

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

    等于

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

    instance1 != instance2

    改为单例

    object CacheInterface{
    ...
    }
    

    使用

    CacheInterface.storeBitmap("key1",bitmap)
    CacheInterface.getBitmap("key1")
    

    【讨论】:

      【解决方案3】:

      是的。我将在这里分享我感到困惑的地方,以防万一有人也是。

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

      【讨论】:

        猜你喜欢
        • 2015-10-14
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-06-14
        • 2014-08-19
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多