Thursday, April 14, 2011

Memory Leak plugged

Alright. I got it fixed. Wahoo.

As mentioned in my previous post, I was noticing that several objects seemed to hang around across screen orientation changes (ie. going from landscape <--> portrait mode). I went back to square one with the original code that I derived my slide rule app from and discovered that *it* also had the memory leak. It didn't exhibit the same issues as my app, however, because it was using way less memory -- all it did was draw a stinking little icon to the screen.

So, I started tracing things which led me to a class based on a Thread object. It turns out that this guy had some references to a Context object. Yesterday I had read several articles that mentioned keeping references to Context when there is a screen change leads to bad juju. Beyond that -- the orientation causes the Activity to be killed, but if there is a reference somewhere to a Context, the old object doesn't disappear. After a bit, this adds up and eventually you have no more memory that can be allocated.

I updated the Thread such that when it needed to be destroyed, it got rid of its references to the Context (and another object it was referencing... just to be safe.) Further, it turned out that the View that presents the graphics was causing the Thread itself to hang around. I had to get rid of that reference as well to shake loose the Thread.

After making those updates and using the DDMS to dump the heap, I still saw that the 3 primary objects in the App (the Thread, the View, and the Activity) were ratcheting up. HOWEVER, this time around forcing the Garbage Collector to execute caused those bad boys to drop back down to 1 each -- which is what I desired. Wahoo! Problem solved!

If you are a visual person, here are some screen shots that highlight the general approach I took in debugging things.

No comments:

Post a Comment