leakcanary icon indicating copy to clipboard operation
leakcanary copied to clipboard

LeakCanary should limit itself to a single heap dump + analysis at a time

Open pyricau opened this issue 5 months ago • 1 comments

Description

When using the worker manager setup, we can end up with several heap analysis running in parallel, and also the heap dumping while a heap analysis is in progress. This can put too much memory pressure on the current process as well as slow down analysis significantly as the N threads race for CPU resources.

Heap dumping is capped to once per minute, source: https://github.com/square/leakcanary/blob/main/leakcanary/leakcanary-android-core/src/main/java/leakcanary/internal/HeapDumpTrigger.kt#L421C5-L421C57

However, if the analysis isn't done before the minute is done, we'll then dump again, and start another analysis.

We could tag the work to check if the analysis is still in progress, although that's a bit tricky with the layers of abstraction. https://developer.android.com/develop/background-work/background-tasks/persistent/getting-started/define-work

pyricau avatar Jul 22 '25 13:07 pyricau

temporary work around

/**
 * Blocks heap dumping while an analysis is in progress.
 */
class HeapDumpingAnalysisBlockingListener : EventListener {

  override fun onEvent(event: EventListener.Event) {
    when (event) {
      is EventListener.Event.HeapDump -> {
        LeakCanary.config = LeakCanary.config.run {
          copy(dumpHeap = false)
        }
      }

      is EventListener.Event.HeapAnalysisDone<*> -> {
        LeakCanary.config = LeakCanary.config.run {
          copy(dumpHeap = true)
        }
      }

      else -> {}
    }
  }
}

pyricau avatar Nov 03 '25 09:11 pyricau