2

The Bitmap memory problem in Android has led me to implement a custom loader and downloader class that will download an image from the web, store a local copy, and create a Bitmap if requested to do so from the local copy. I'm keeping these in a list of SoftReference<T> so that they are kept for a while, then garbage collected, at which point the class's finalize() method is called:

protected void finalize() throws Throwable {
    Log.w("IMAGEPACK", "Finalizing " + mBitmap);
    if(mBitmap!=null&&!mBitmap.isRecycled()) mBitmap.recycle();
    super.finalize();
}

Looking at LogCat I've determined that this piece of code is happening right before the crash. I've also stepped through the code and it's on this line that it fails.

I had a solution that used synchronized reference counting previously, and which seemed pretty reliable, but having had big problems with manually-written reference-counting before I wanted to avoid this. I may have to revert to it, but I would like to know WHY bitmap recycling is failing here.

I am currently testing on a Samsung Galaxy S on 2.3.3.

Mat
  • 202,337
  • 40
  • 393
  • 406
Andrew Wyld
  • 7,133
  • 7
  • 54
  • 96

1 Answers1

0

You actually don't need to call recycle() if you lose the reference to be Bitmap. The Bitmap class is already overriding finalize() and deallocating the memory so what you're doing is redundant.

Also, according to the docs itself:

This is an advanced call, and normally need not be called, since the normal GC process will free up this memory when there are no more references to this bitmap.

Recycle exists if you don't need the bitmap anymore, but for whatever reason you need to keep the reference around (perhaps you're overloading the Bitmap object with extra meta-data that you want to keep). If you're just holding a reference to the Bitmap object, then dereferencing it is enough.

DeeV
  • 35,865
  • 9
  • 108
  • 95
  • Thanks for this, but bitter, bitter experience has shown that this is not in fact the case. I spent a long time chasing a memory leak in another application that was traceable to unrecycled `Bitmap`s, which I had assumed would be garbage collected when I stopped referring to them. – Andrew Wyld Oct 12 '12 at 17:13