When should I recycle a bitmap using LRUCache?

I believe that when the LRUCache evicts an image to make room for another one, the memory is not being freed.

It won’t be, until the Bitmap is recycled or garbage-collected.

A quick google search reveals that this is happening because the image which is displaying has been recycled.

Which is why you should not be recycling there.

Why are recycled images still in the LRUCache if I’m only recycling them after they’ve been removed?

Presumably, they are not in the LRUCache. They are in an ImageView or something else that is still using the Bitmap.

What is the alternative for implementing a cache?

For the sake of argument, let’s assume you are using the Bitmap objects in ImageView widgets, such as in rows of a ListView.

When you are done with a Bitmap (e.g., row in a ListView is recycled), you check to see if it is still in the cache. If it is, you leave it alone. If it is not, you recycle() it.

The cache is simply letting you know which Bitmap objects are worth holding onto. The cache has no way of knowing if the Bitmap is still being used somewhere.

BTW, if you are on API Level 11+, consider using inBitmap. OutOMemoryErrors are triggered when an allocation cannot be fulfilled. Last I checked, Android does not have a compacting garbage collector, so you can get an OutOfMemoryError due to fragmentation (want to allocate something bigger than the biggest single available block).

Leave a Comment