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;
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...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With