SoftReference gets garbage collected too early(SoftReference 过早地收集垃圾)
问题描述
我正在为我的 Android 应用程序实现缓存机制.
I'm on my way with implementing a caching mechanism for my Android application.
我使用 SoftReference
,就像我找到的许多示例一样.问题是,当我在 ListView
中向上或向下滚动时,大部分 图像已被清除.我可以在 LogCat 中看到每次应用程序加载新图像时都会对我的应用程序进行垃圾收集.这意味着 ListView
中大部分 的不可见图像都消失了.
I use SoftReference
, like many examples I've found. The problem is, when I scroll up or down in my ListView
, the most of the images are already cleared. I can see in LogCat that my application is garbage collected everytime the application loads new images. That means that the most of the non-visible images in the ListView
are gone.
所以,每次我回滚到较早的位置(我之前真正下载过图片的地方)我都必须再次下载图片 - 它们不是 缓存.
So, everytime I scroll back to an earlier position (where I really downloaded images before) I have to download the images once again - they're not cached.
我也研究过这个话题.根据本文中的 Mark Murphy 所述,SoftReference
似乎存在(或曾经?)一个错误.其他一些结果表明相同的事情(或相同的结果);SoftReference
清除得太早了.
I've also researched this topic. According to Mark Murphy in this article, it seems that there is (or was?) a bug with the SoftReference
. Some other results indicates the same thing (or the same result); SoftReference
s are getting cleared too early.
有什么可行的解决方案吗?
推荐答案
SoftReference 是可怜的 mans Cache.JVM 可以使这些引用保持更长时间,但不是必须的.一旦不再有硬引用,JVM 就可以垃圾收集软引用的对象.您遇到的 JVM 的行为是正确的,因为 JVM 不必将此类对象保留更长时间.当然,大多数 JVM 都试图在一定程度上保持软引用对象的存活.
SoftReference are the poor mans Cache. The JVM can hold those reference alive longer, but doesn't have to. As soon as there's no hard reference anymore, the JVM can garbage collect a the soft-referenced Object. The behavior of the JVM you're experiencing is correct, since the JVM doesn't have to hold such object longer around. Of course most JVMs try to keep the soft reference object alive to some degree.
因此,SoftReferences 是一种危险的缓存.如果你真的想确保缓存行为,你需要一个真正的缓存.就像一个 LRU-cache.特别是如果您的缓存对性能至关重要,您应该使用适当的缓存.
Therefore SoftReferences are kind of a dangerous cache. If you really want to ensure a caching-behavior, you need a real cache. Like a LRU-cache. Especially if you're caching is performance-critical, you should use a proper cache.
这篇关于SoftReference 过早地收集垃圾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:SoftReference 过早地收集垃圾
基础教程推荐
- Java Keytool 导入证书后出错,"keytool error: java.io.FileNotFoundException &拒绝访问" 2022-01-01
- 如何使用 Java 创建 X509 证书? 2022-01-01
- 降序排序:Java Map 2022-01-01
- Java:带有char数组的println给出乱码 2022-01-01
- 无法使用修饰符“public final"访问 java.util.Ha 2022-01-01
- 设置 bean 时出现 Nullpointerexception 2022-01-01
- 在 Libgdx 中处理屏幕的正确方法 2022-01-01
- FirebaseListAdapter 不推送聊天应用程序的单个项目 - Firebase-Ui 3.1 2022-01-01
- “未找到匹配项"使用 matcher 的 group 方法时 2022-01-01
- 减少 JVM 暂停时间 >1 秒使用 UseConcMarkSweepGC 2022-01-01