Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Bitmap, Bitmap.recycle(), WeakReferences, and Garbage Collection

Tags:

AFAIK on Android, it is recommended to reference Bitmap objects as WeakReferences in order to avoid memory leaks. When no more hard references are kept of a bitmap object, the garbage collector will automatically collect it.

Now, if I understand correctly, the method Bitmap.recycle() must always be called to free a Bitmap. I think this is because Bitmap objects have special memory management.

Is that correct?

If this is true, when using WeakReferences, there must be memory leaks because Bitmap.recycle() is never called when the WeakReferences are freed. Or, somehow, are WeakReferences sufficient to avoid memory leaks?

Thanks

like image 216
Sly Avatar asked Feb 10 '11 16:02

Sly


1 Answers

Bitmap.recycle isn't required to be called, as the garbage collector will clean up bitmaps on its own eventually (as long as there are no references). Bitmaps in Android are created in native memory, not on the VM heap, so the actual bitmap object on the VM heap is very small as it doesn't contain any actual bitmap data. (EDIT: no longer the case as of Android 3.0+) The real size of the bitmap will still be counted against your heap usage for purposes of GC and making sure your app doesn't use too much memory.

However, the GC seems to be a little moody when it comes to Bitmaps. If you just remove all hard references, it would sometimes (in my case) hang onto the Bitmaps for a little while longer, perhaps because of the weird way Bitmap objects are allocated/counted. Bitmap.recycle seems to be good for getting the GC to collect that object more quickly.

Either way, you won't leak memory if you don't call Bitmap.recycle as long as you don't keep hard references accidentally. You may encounter OutOfMemoryErrors if you try to allocate too many bitmaps at once or too large bitmaps without calling recycle, though.

EDIT: It is important to note that as of Android 3.0, Bitmaps are no longer allocated in native memory. The are allocated on the VM heap like any other Java object. However, what I said about not needing to call recycle still applies.

like image 162
Victor Avatar answered Oct 21 '22 16:10

Victor