Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android - Bitmap and memory management?

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;
like image 787
aryaxt Avatar asked Jan 25 '12 01:01

aryaxt


2 Answers

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...

like image 115
mfeingold Avatar answered Oct 31 '22 05:10

mfeingold


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.

like image 3
Navin Ilavarasan Avatar answered Oct 31 '22 06:10

Navin Ilavarasan