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.mdCopie 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
Para Claude Code, Codex ou Cursor: rode na pasta do projeto e a skill fica instalada.
Baixe o SKILL.md e coloque na pasta de skills do seu agente.
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
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-checksto 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.
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: UNKNOWNnodes in between to find where the chain should be broken.
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.
Apply Fix Patterns:
- Pattern 1: Explicit Unregistration:
- If the leak is due to an observer not being removed, ensure
removeObserver()is called inonDestroy()or equivalent lifecycle teardown. - If the component is not a
DestroyObserver, consider making it one and registering it withActivityLifecycleDispatcher.
- If the leak is due to an observer not being removed, ensure
- Pattern 2: Nullifying References:
- If a field causes leaks after destruction, nullify it in
onDestroy(). - Preferred approach: Mark the field as
@Nullableand add explicit null checks where needed. This is safer and satisfies NullAway without suppressions. - Alternative approach: If marking the field
@Nullablecauses too much "collateral damage" (requiring null checks in many places), you can use@SuppressWarnings("NullAway")on theonDestroy()method to set the field tonullwhile 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 }
- If a field causes leaks after destruction, nullify it in
- 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.
- If cleanup requires mutating state (e.g., calling
- Pattern 1: Explicit Unregistration:
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
- Rebuild the test target:
Best Practices & Gotchas
- Order of Destruction: Nullifying references in
onDestroy()can causeNullPointerExceptions if other components try to use them during their own destruction (e.g., to unregister observers). Ensure that cleanup methods likeunregisterObserverhandle 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
Comentários
- …
Mais skills deste repositório
fuzzing
25 milAjuda seu agente a escrever testes de fuzzing que alimentam o código com muitas entradas aleatórias para encontrar falhas e bugs em código C++.
gn-deps-debugging
25 milAjuda seu agente a corrigir erros de build causados por dependências ausentes ou incorretas em arquivos de build GN, sem adicionar dependências amplas e desnecessárias.
jni-type-conversion
25 milAjuda seu agente a substituir o código manual de conversão de Java para C++ por anotações @JniType mais simples em código Android.
loadline
25 milAjuda seu agente a rodar benchmarks do LoadLine que medem a velocidade de carregamento de páginas web no Android e no Chrome para desktop.
Skills parecidas
android-clean-architecture
280 milFaz seu agente organizar projetos Android de forma eficiente. Ele estrutura o código para facilitar a manutenção e o desenvolvimento de novos recursos.
compose-multiplatform-patterns
280 milAjuda seu agente a usar Compose Multiplatform e Jetpack Compose em projetos KMP. Cobre estado, navegação, temas e performance.
dart-flutter-patterns
280 milFaz seu agente escrever código para apps Dart e Flutter. Ele usa padrões modernos para criar apps robustos e fáceis de gerenciar.