Skip to content

Timer tasks as memoryleak cause in Android

by peterdk on May 30th, 2013

I was struggling today with a memoryleak in a application I am building for a client. The app is very heavy on memory, because it uses a lot of images.

It took me more than a hour to find the cause of it. It turns out that I didn’t cancel my Timer.scheduleAtFixedRate() TimerTask that updated a dynamic part of my UI.

If you are struggling with memoryleaks as well, make sure you install the eclipse addon : “Memory Analyzer”. If you have that one installed, you can use DDMS in Eclipse to dump a hprof file, which automatically get’s opened and you can then get lots of usefull info on your leaks. Use the “dominator tree” to show the largest items in memory, and right click on them and select “Path to GC roots => With all references” This shows what’s keeping them in memory.

I couldn’t find my leaks at first, because the Path to GC roots, didn’t include any obvious Context leaks or so (the normal stuff that causes memory leaks: static Context/Activity values). ¬†However, after an hour I realized that the “TimerTask” I first dismissed as some Android internal stuff, actually was the cause of my issues.

I then made sure to “cancel()” my timertask in my activity’s “onDestroy()” method, and things turned to normal!

From → Android, Programming

No comments yet

Leave a Reply

Note: XHTML is allowed. Your email address will never be published.

Subscribe to this comment feed via RSS