Posts Tagged ‘memory leak’


21.03.2011

Memory leak and Android / Java

posted by Karsten

in Uncategorized

Many (novice) programmers think that managed environments, such as Java, is memory leak free. The Garbage collector (GC) will just take care of all memory management, and everyone will be happy! Over the last few days I’d have wished this was the case…

The reason this isn’t true is that if something is referencing the object which is not in use, the GC can’t clean it up, and you can potentially end up with a mountain of wasted memory. Last Friday I suddenly realised that I might have been a bad boy and created one of these situations within my game. I could only play 10-15 games in a row on my machine and then it would crash with a heap allocation error. This is typically what will happen in this situation.

Obviously I thought that I’d been cleaning up within my code, but something was a miss. It took me many hours to fix this one, and I believe it is worthwhile mentioning this one, as it is a problem others are likely to get caught in!

The situation:

  • To minimise memory usage bitmaps are referenced statically within classes
  • One of these are used as background within a view set using setBackgroundDrawable(Drawable d)

What happens here is that a callback is create from the static bitmap to the view, so when the view object is nullified or goes “out of sight” there still exist a callback from the static bitmap to the view (even if is within a class not in use). Therefore the GC cannot cleanup the view object, and through that the context is reference, which means pretty much everything you’ve created within your view. For me that meant 4 full background images, and on a phone that means a lot of memory…

Therefore, this callback needs to be cleaned up manually!

Share