Pular para o conteúdo
Skillpedia
Apps de celular25 mil · #10059

java-memory-leaks

O que ela faz

Esta skill orienta sua IA a descobrir por que um app Android mantém memória que deveria liberar. Ela é indicada para desenvolvedores Android que veem relatórios de vazamento em seus testes.

Quando usar

  • ✓Quando um log de teste mostra um relatório de vazamento de memória do LeakCanary.
  • ✓Quando uma tela ou componente do Android parece permanecer na memória depois de fechar.
  • ✓Quando você precisa ler um rastro de vazamento e encontrar o objeto que deveria ser liberado.

Link da skill

https://github.com/chromium/chromium/blob/main/agents/skills/java-memory-leaks/SKILL.md

Copie e cole na sua IA (Claude, ChatGPT ou Cursor) pedindo para seguir as instruções.

Como usar

O jeito mais fácil: copie a mensagem e cole na sua IA. Ela lê a skill e segue as instruções.

Mensagem pronta para colar

Use esta skill para me ajudar: https://github.com/chromium/chromium/blob/main/agents/skills/java-memory-leaks/SKILL.md Leia o arquivo SKILL.md desse link e siga as instruções dele na minha tarefa.
Quer que a sua IA encontre skills como esta sozinha?Instale o MCP grátis do Skillpedia: uma linha, e ela pesquisa entre 15.000+ skills antes de cada tarefa.Instalar em 1 minuto →

Exemplo do que pedir para a IA

“Meu teste Android mostra um vazamento do LeakCanary. Você pode ler o rastro e me ajudar a corrigir?”

5 skills novas por semana. 1 minuto de leitura.

Como funciona

A IA confirma o vazamento executando o teste, lê o rastro de vazamento da raiz até o objeto que vaza, encontra a referência que deveria ser limpa e propõe uma correção.

Conteúdo técnico (SKILL.md original)

Texto original do autor, em inglês, direto do GitHub.

Fixing Java Memory Leaks in Android Chrome

This skill guides the process of identifying, debugging, and fixing Java memory leaks in Android Chrome, typically identified by LeakCanary in instrumentation tests.

Workflow

  1. Confirm the Leak:

    • If you suspect a leak, confirm it by adding or running an instrumentation test that exercises the component.
    • If the leak does not reproduce and the test has @Batch, it may be necessary to run the whole test class to reproduce the leak.
    • Critical: Pass --enable-leak-checks to the test runner if the class lacks @EnableLeakChecks.
    • Run the test and look for LeakCanary detections in the log output.
    • Do not get sidetracked by other crashes, or even other leaks. Report these, but do not try to fix them unless they seems to be variations of the suspected leak.
  2. Analyze Leak Trace:

    • Examine the LeakCanary trace from the test failure log.
    • Identify the leaking object (usually at the bottom of the trace, marked with Leaking: YES).
    • Identify the GC Root (at the top of the trace).
    • Trace the retention path from the GC Root to the leaking object.
    • Look for Leaking: UNKNOWN nodes in between to find where the chain should be broken.
  3. Identify the Break Point:

    • Look for references that should be cleared when the activity or component is destroyed.
    • Common culprits:
      • Observers not unregistered.
      • Missing calls to destroy() on components that hold resources or observers.
      • Static variables holding references to activities or contexts.
      • Inner classes (especially anonymous ones) holding implicit references to the outer class.
      • Callbacks passed to long-lived components without lifecycle management.
  4. Apply Fix Patterns:

    • Pattern 1: Explicit Unregistration:
      • If the leak is due to an observer not being removed, ensure removeObserver() is called in onDestroy() or equivalent lifecycle teardown.
      • If the component is not a DestroyObserver, consider making it one and registering it with ActivityLifecycleDispatcher.
    • Pattern 2: Nullifying References:
      • If a field causes leaks after destruction, nullify it in onDestroy().
      • Preferred approach: Mark the field as @Nullable and add explicit null checks where needed. This is safer and satisfies NullAway without suppressions.
      • Alternative approach: If marking the field @Nullable causes too much "collateral damage" (requiring null checks in many places), you can use @SuppressWarnings("NullAway") on the onDestroy() method to set the field to null while keeping it non-null for the rest of the lifecycle.
      • Example (Preferred):
        private @Nullable CustomTabActivityTabProvider mTabProvider;
        
        @Override
        public void onDestroy() {
            mTabProvider = null; // Breaks leak trace
        }
        
    • Pattern 3: Avoid Mutation in Observers:
      • If cleanup requires mutating state (e.g., calling removeTab()), ensure this is done by the owner of the component, not by an observer or registrar. Observers should not have side effects that mutate the observed object during teardown.
  5. Verify:

    • Rebuild the test target: autoninja -C out/Debug chrome_public_test_apk.
    • Run the specific leak test: out/Debug/bin/run_chrome_public_test_apk --enable-leak-checks -f "YourLeakTest*".
    • Verify that LeakCanary no longer reports the leak.
    • Trybot Verification: To run the LeakCanary bot on CQ / trybots, include the following footer in the CL description: Cq-Include-Trybots: luci.chromium.try:android-16-x64-leakcanary-rel

Best Practices & Gotchas

  • Order of Destruction: Nullifying references in onDestroy() can cause NullPointerExceptions if other components try to use them during their own destruction (e.g., to unregister observers). Ensure that cleanup methods like unregisterObserver handle null references gracefully.
    public void unregisterActivityTabObserver(CustomTabTabObserver observer) {
        mActivityTabObservers.removeObserver(observer);
        if (mTabProvider == null) return; // Guard against NPE during destruction
        Tab activeTab = mTabProvider.getTab();
        ...
    }
    

Examples

Nullifying References

Perguntas frequentes

O que é um vazamento de memória?

Um vazamento de memória acontece quando o app mantém objetos na memória depois que não precisa mais deles. Com o tempo, isso pode deixar o app lento ou fazê-lo travar.

O que é o LeakCanary?

O LeakCanary é uma ferramenta que detecta vazamentos de memória em apps Android e escreve um rastro mostrando o que segura o objeto.

Preciso saber Java para usar isto?

Sim, a skill funciona com código Java no Android. Sua IA faz a leitura do rastro e as mudanças no código.

Detalhes

Descrição original do autor

How to identify and fix Java memory leaks in Android Chrome using LeakCanary traces.

repo: chromium/chromium

Popularidade

Estrelas no GitHub
25 mil
Posição no ranking
#10059
Licença
BSD-3-Clause
Atualizada em
02/11/2026

Essa skill é útil?

0

Entre para votar.

Comentários

  • …

Mais skills deste repositório

Skills parecidas