Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Diff b/w bitmap.recycle() and bitmap=null

I am in a situation where I have used a for loop to download a set of images and I am converting it into bitmap images. So in order to avoid OutOfMemory error, I am trying to recycle the bitmaps. But unfortunately I am running into another exception saying something like "View trying to use a recycled bitmap".

But still I am allowed to null the used bitmap by using bitmap=null. So my question is, will making my bitmap null help me in freeing up the used memory? or should I provide bitmap.recycle() in some other part of my code?

like image 367
Andro Selva Avatar asked Jun 07 '11 05:06

Andro Selva


People also ask

What is bitmap recycle?

If you're displaying large amounts of bitmap data in your app, you're likely to run into OutOfMemoryError errors. The recycle() method allows an app to reclaim memory as soon as possible. Caution: You should use recycle() only when you are sure that the bitmap is no longer being used.

How do you clear a bitmap?

You can use eraseColor on bitmap to set its color to Transparent. It will useable again without recreating it.


2 Answers

There is no guaranteed way to force a garbage collection, only a way to suggest one using System.gc(). Since the bitmaps pixel data lives in native memory outside of the dalvik heap, providing a native function (in this case recycle()) will give us the opportunity to clean up this pixel data for sure (eventually). Please note that when using recycle() there is not much more you can do with that bitmap.

The issue you are having is that you are calling recycle() on a bitmap, which you are still trying to use.

To answer your question, yes, setting bitmap to null after you have recycled it is a good idea, but it may also be redundant. Always try to recycle your bitmaps when you are done with them.

like image 97
nicholas.hauschild Avatar answered Oct 07 '22 06:10

nicholas.hauschild


Calling recycle() indicates to the system that you are finished using that resource and that the system may now free the unmanaged memory that it was using. Once you have disposed of a resource in this way, its behaviour is usually undefined (one would reasonably expect it to simply no longer work).

Setting the reference to null afterwards has two benefits:

  • You won't have stale references to objects that won't work when you try to use them
  • The garbage collector will know to clean up the managed side of the bitmap object, freeing even more memory
like image 45
Tullo_x86 Avatar answered Oct 07 '22 07:10

Tullo_x86