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?

Alexander Abakumov
  • 13,617
  • 16
  • 88
  • 129
android developer
  • 114,585
  • 152
  • 739
  • 1,270
  • 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(). – Bitcoin Cash - ADA enthusiast Oct 12 '14 at 23:02
  • @Tiago You can watch this lecture: https://www.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). – android developer Oct 13 '14 at 06:43
  • 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! – Bitcoin Cash - ADA enthusiast Oct 13 '14 at 20:03
  • @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: https://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: https://code.google.com/p/android-developer-preview/issues/detail?id=1519 – android developer Oct 13 '14 at 20:44

1 Answers1

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.

John Conde
  • 217,595
  • 99
  • 455
  • 496
s0nicYouth
  • 470
  • 3
  • 15