Android - Bitmap and memory management?

2019-01-25 07:04发布

问题:

I've seen in a lot of samples, that developers call recycle() on bitmap, and then set it to null. Why is this necessary, doesn't the garbage collector take care of releasing the bitmap?

Bitmap bitmap = BitmapFactory.decodeStream(inputStream);
bitmap.recycle();
bitmap = null;

回答1:

Join the club. It kind of does but not quite.

The thing is that in the pre-Honeycomb versions of Android the memory for bitmaps was (is) allocated from unmanaged memory, which creates all sorts of problems. It is still released but from the finalizer of the bitmap object implementation. Which means that it will take at least 2 passes of GC to collect it. Also if for whatever reason the finalizer fails to execute - you got the picture. Another thing is - it is really difficult to trace - DDMS does not see it and neither does MAT

For Android 3.0 this has been changed and bitmaps are implemented over managed byte arrays, but for the older phones...



回答2:

bitmap.recycle(); release the native heap that is used in bitmaps.And setting it to null is to assist the GC to quickly collect your reference.



回答3:

From docs at http://developer.android.com/reference/android/graphics/Bitmap.html#recycle%28%29.


Free the native object associated with this bitmap, and clear the reference to the pixel data. This will not free the pixel data synchronously; it simply allows it to be garbage collected if there are no other references. The bitmap is marked as "dead", meaning it will throw an exception if getPixels() or setPixels() is called, and will draw nothing. This operation cannot be reversed, so it should only be called if you are sure there are no further uses for the bitmap. 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.


So it doesn't seem to be necessary to call. The only time I've ever heard a need to manually set an object to null is if its a static variable (or some variable that won't go out of scope easily) and you want to force it out of memory. Maybe if you are continuously allocating bitmaps rapidly there may be a need to try and force garbage collection, but for the majority of cases it is probably not needed.



回答4:

This article from android development docs has a lot of information on this topic. While you're at it also check the article about caching if you'll be using multiple bitmaps.