java-memory-leaks
Qué hace
Esta skill guía a tu IA para averiguar por qué una app Android retiene memoria que debería liberar. Está pensada para desarrolladores Android que ven informes de fugas en sus pruebas.
Cuándo usarla
- ✓Cuando un registro de pruebas muestra un informe de fuga de LeakCanary.
- ✓Cuando una pantalla o componente Android parece seguir en memoria después de cerrarse.
- ✓Cuando necesitas leer una traza de fuga y encontrar el objeto que debería liberarse.
Link de la skill
https://github.com/chromium/chromium/blob/main/agents/skills/java-memory-leaks/SKILL.mdCópialo y pégalo en tu IA (Claude, ChatGPT o Cursor) pidiéndole que siga las instrucciones.
Cómo usar
La forma más fácil: copia el mensaje y pégalo en tu IA. Ella lee la skill y sigue las instrucciones.
Mensaje listo para pegar
Para Claude Code, Codex o Cursor: ejecútalo en la carpeta del proyecto y la skill queda instalada.
Descarga el SKILL.md y ponlo en la carpeta de skills de tu agente.
Ejemplo de qué pedirle a la IA
“Mi prueba de Android muestra una fuga de LeakCanary. ¿Puedes leer la traza y ayudarme a arreglarla?”
5 skills nuevas por semana. 1 minuto de lectura.
Cómo funciona
La IA confirma la fuga ejecutando la prueba, lee la traza de la fuga desde la raíz hasta el objeto que se filtra, encuentra la referencia que debería borrarse y propone un arreglo.
Contenido técnico (SKILL.md original)
Texto original del autor, en inglés, directo de 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
Preguntas frecuentes
¿Qué es una fuga de memoria?
Ocurre cuando una app mantiene objetos en memoria aunque ya no los necesita. Con el tiempo puede ralentizar la app o hacer que se cierre.
¿Qué es LeakCanary?
Es una herramienta que detecta fugas de memoria en apps Android y escribe una traza que muestra qué retiene el objeto.
¿Tengo que saber Java para usarla?
Sí. La skill funciona con código Java en Android. Tu IA se encarga de leer la traza y de hacer los cambios de código.
Detalles
Descripción original del autor
How to identify and fix Java memory leaks in Android Chrome using LeakCanary traces.
repo: chromium/chromium
Popularidad
- Estrellas en GitHub
- 25 mil
- Posición en el ranking
- #10059
- Licencia
- BSD-3-Clause
- Actualizada
- 2/11/2026
Comentarios
- …
Más skills de este repositorio
fuzzing
25 milAyuda a tu agente a escribir pruebas de fuzzing que introducen muchas entradas aleatorias en el código para encontrar fallos y errores en C++.
gn-deps-debugging
25 milAyuda a tu agente a arreglar errores de compilación por dependencias que faltan o son incorrectas en archivos GN, sin añadir dependencias amplias.
jni-type-conversion
25 milAyuda a tu agente a reemplazar código manual de conversión de Java a C++ por anotaciones @JniType más simples en código Android.
loadline
25 milAyuda a tu agente a ejecutar pruebas de rendimiento LoadLine que miden la velocidad de carga de páginas web en Chrome de Android y de escritorio.
Skills parecidas
android-clean-architecture
280 milHace que tu agente organice proyectos de Android de forma eficiente. Estructura el código para facilitar el mantenimiento y el desarrollo de nuevas funciones.
compose-multiplatform-patterns
280 milAyuda a tu agente a usar patrones de Compose Multiplatform y Jetpack Compose en proyectos KMP, incluyendo estado, navegación, temas y rendimiento.
dart-flutter-patterns
280 milHace que tu agente escriba código para apps de Dart y Flutter. Usa patrones modernos para crear apps robustas y fáciles de mantener.