SoftReference太早收集垃圾 [英] SoftReference gets garbage collected too early

查看:77
本文介绍了SoftReference太早收集垃圾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在为我的Android应用程序实现一个缓存机制。

我使用 SoftReference ,就像我找到的许多例子。问题是,当我在 ListView 中向上或向下滚动时,大多数图像已被清除。我可以在LogCat中看到,每次应用程序加载新图像时,我的应用程序都会被垃圾收集。这意味着 ListView 中的大多数不可见图像都消失了。因此,每当我向前滚动时(我之前真的下载过图像),我必须再次下载图像 - 他们'缓存。



我也研究过这个主题。 根据本文中的Mark Murphy ,似乎存在(或者是)与 SoftReference 有关的错误。其他一些结果表明同样的事情(或相同的结果); SoftReference s正在被清除太早。



有没有可行的解决方案?

解决方案

SoftReference是可怜的人类缓存。 JVM可以更长时间地保存这些引用,但不一定。只要没有硬引用,JVM就可以垃圾收集软引用的对象。您所遇到的JVM的行为是正确的,因为JVM不必长时间持有这样的对象。当然,大多数JVM试图在一定程度上保持软参考对象的活性。

因此,SoftReferences是一种危险的缓存。如果你真的想确保缓存行为,你需要一个真正的缓存。就像一个 LRU缓存。特别是如果你的缓存是性能关键的,你应该使用适当的缓存。


I'm on my way with implementing a caching mechanism for my Android application.

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.

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); SoftReferences are getting cleared too early.

Is there any working solution?

解决方案

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.

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太早收集垃圾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆