What does calling bitmap.recycle() on API 11+ do?
Asked Answered
G

1

7

I know that before API 10 of Android, it was important to call recycle() for Bitmaps that aren't used anymore, since the actual raw data is stored in the native memory.

However, as of API 11, Bitmaps are stored in the heap, so my question is:

Is it still needed to call recycle() on Bitmaps if the API is large enough (at least 11)? What does it do if I call it on such API?

Gavel answered 14/8, 2012 at 14:24 Comment(4)
When you say "it was important to call recycle() before API 10" does that mean that if you don't the memory will never be freed? The official docs say it is "recommended" but if it allocates the bitmap in the native memory I don't understand how it can get freed without a call to recycle().Hothead
@Tiago You can watch this lecture: youtube.com/watch?v=_CruQY55HOk#t=656 . Bitmaps took really small space in the heap, but their pixel data didn't (yet was a part of the OOM mechanism of the heap), so the GC didn't know how good/bad is the situation, and if it wasn't triggered while creating multiple bitmaps, you could easily get OOM. This is why it's important to call "recycle", so that it will clean bitmaps as soon as possible (because the GC didn't do its job well).Gavel
Ah, I see. That explains a lot. It is quite strange that the OutOfMemory exception would count for both the heap and the native memory while the GC would only look at the heap. Once from Honeycomb+ the pixel data of the bitmaps are also in the heap, then the GC can do its job right. What a mess, hehe! Thanks for clarifying!Hothead
@Tiago Yes, I don't know what they were thinking about when they got this weird behavior. If you do wish to store bitmaps via JNI, you can try my tiny, humble library: github.com/AndroidDeveloperLB/AndroidJniBitmapOperations . An example of how to cause an app to leak memory from JNI (and what it causes) can be found here: code.google.com/p/android-developer-preview/issues/…Gavel
C
6

Official documentation tells that recycle() now is an advanced call so if you want to free your bitmap you can just write something like bitmap = null and GC will take care of everything else.

Conard answered 18/10, 2012 at 14:10 Comment(2)
i see . so recycle will still free the memory of it right away?Gavel
Yes, recycle will free memory not looking at GC, so you have to be careful with this call.Conard

© 2022 - 2024 — McMap. All rights reserved.