android - 使用 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
据我了解,缓存会一直存储到用户删除(手动或卸载应用程序),或者当超过允许的空间时被系统清除。我错过了什么?
解决方案
LruCache
对象只是在内存中存储对对象的引用。一旦失去对 的引用,该缓存中LruCache
的LruCache
对象和所有对象都会被垃圾回收。磁盘上没有存储任何内容。
推荐阅读
- arrays - 使用 kotlin 如何将数组附加到二维数组
- python-3.x - 为什么 print 函数在方法中不起作用:get_details() 并且没有为 print(x.increment_odometer) 返回?
- c# - 如何正确键入声明为类属性的 LINQ 请求?
- html - 将表头与引导程序 4 上的表内容对齐
- swift - 如何将 FScalendar 选择的日期更改为渐变色?
- django - 我如何将一些数据播种到我的表中,这些数据是从 Django 中的特定外部 api 获取的?
- laravel - 如何使用子文件夹/域部署项目 laravel
- javascript - 自定义浮动或固定滚动条/DIV 条
- appium - Appium设置问题
- python - 如何使用calmap和斧头上的颜色条绘制热图?