Badoo Dima Voronkevych Feb 28, 2017

Android Handler Memory Leaks

Article Summary

Dima Voronkevych from Bumble's Android team reveals how a simple Handler.postDelayed() call created 7 Activity instances in memory when only 1 should exist. The garbage collector couldn't save them.

This deep dive from Bumble's engineering team dissects Android Handler memory leaks using heap dumps and real examples. Voronkevych walks through why anonymous Runnables posted to Handlers prevent Activities from being garbage collected, even after rotation, and tests multiple solutions with memory analysis.

Key Takeaways

Critical Insight

Handler memory leaks occur when posted Messages keep Activities alive through reference chains, but can be eliminated with proper cleanup patterns or Bumble's open source WeakHandler library.

The article includes a detailed diagram showing exactly how WeakHandler breaks the reference chain differently than standard Handlers.

About This Article

Problem

Badoo's Android team found that when Runnables are posted with delays to Handler queues, they create reference chains through Message objects back to the main thread's Looper. This prevents Activities from being garbage collected even after screen rotation.

Solution

Badoo built WeakHandler, an open-source library that wraps Runnables in WeakRunnable objects. The library keeps hard references to the Handler itself, which lets Activities get collected once the Handler is no longer reachable.

Impact

Memory dumps showed the number of Activity instances in memory dropped from seven down to one after WeakHandler was implemented. The Handler-induced memory leak was completely eliminated without needing any manual cleanup code.