jambit Toilet Paper Memory Leaks in Android-Apps

Early detection of memory leaks in Android apps with the LeakCanary Library

Problem: Memory Leaks are hard to detect

Nobody likes memory leaks. They are usually difficult to reproduce, even harder to identify and, in worst case, after long usage they only become noticeable with an OutOfMemoryException.

Solution: Android Studio and the LeakCanary Library

Detecting Memory Leaks in Android Studio

Fortunately, there are several ways to detect leaks in Android. One possibility is an internal offer by Android Studio: with the help of the profiler, the Java heap can be displayed and then analyzed. Since Android Studio 3.6 it can also be filtered specifically for no longer existing but still referenced Activities/Fragments (Activity/Fragment Leaks). Besides the existing instances, the references to them are also displayed, so that conclusions about leaks can be drawn. The screenshot above shows an example application, in which the reference within a singleton is held to one activity, so that the garbage collector cannot clean it up afterwards.

A much more comfortable solution is offered by the library LeakCanary. A WeakReference to different instances is created in debug builds (for example, to Activities in the onActivityDestroyed method). A background thread then checks whether the reference has been cleaned up (after the garbage collector has been executed). If not, the heap is saved in an .hprof file. This is analyzed in a separate process using the previous WeakReference and the chain of references is calculated which prevents the object from freeing up its memory. In LeakCanary, possible causes for the memory leak are highlighted with a red wavy line. This makes it quite easy to detect leaks at an early stage and to narrow down their origin efficiently.

Detecting Memory Leaks with LeakCanary Library

Further aspects


Author: Kevin Stieglitz / Software Engineer / Business Division Automotive World​

Early detection of memory leaks in Android apps with the LeakCanary Library

Wir verwenden Cookies, um unsere Webseite für Sie zu optimieren. Mit dem Besuch unserer Webseite erklären Sie sich damit einverstanden. // Our website is using cookies to improve your experience. By continuing to browse the site, you are agreeing to our use of cookies.

Weitere Informationen finden Sie in unserer Datenschutzerklärung. // For more information, please refer to our privacy policy.

contact icon

Contact us now