java-memory-leaks
Ce qu’il fait
Cette compétence guide votre IA pour comprendre pourquoi une application Android conserve une mémoire qu'elle devrait libérer. Elle s'adresse aux développeurs Android qui voient des rapports de fuite dans leurs tests.
Quand l’utiliser
- ✓Quand un journal de test affiche un rapport de fuite de mémoire LeakCanary.
- ✓Quand un écran ou un composant Android semble rester en mémoire après sa fermeture.
- ✓Quand vous devez lire une trace de fuite et trouver l'objet qui devrait être libéré.
Lien du skill
https://github.com/chromium/chromium/blob/main/agents/skills/java-memory-leaks/SKILL.mdCopiez-le et collez-le dans votre IA (Claude, ChatGPT ou Cursor) en lui demandant de suivre les instructions.
Comment l’utiliser
Le plus simple : copiez le message et collez-le dans votre IA. Elle lit le skill et suit les instructions.
Message prêt à coller
Pour Claude Code, Codex ou Cursor : lancez-la dans le dossier du projet et le skill est installé.
Téléchargez le SKILL.md et placez-le dans le dossier de skills de votre agent.
Exemple de demande à votre IA
“Mon test Android affiche une fuite LeakCanary. Pouvez-vous lire la trace et m'aider à la corriger ?”
5 nouveaux skills par semaine. 1 minute de lecture.
Comment ça marche
L'IA confirme la fuite en lançant le test, lit la trace de fuite depuis la racine jusqu'à l'objet qui fuit, repère la référence qui devrait être libérée, puis propose une correction.
Contenu technique (SKILL.md original)
Texte original de l’auteur, en anglais, directement depuis 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
Questions fréquentes
Qu'est-ce qu'une fuite de mémoire ?
Une fuite de mémoire se produit lorsqu'une application conserve des objets en mémoire alors qu'elle n'en a plus besoin. Avec le temps, cela peut ralentir l'application ou la faire planter.
Qu'est-ce que LeakCanary ?
LeakCanary est un outil qui détecte les fuites de mémoire dans les applications Android et écrit une trace montrant ce qui retient l'objet.
Faut-il connaître Java pour l'utiliser ?
Oui. La compétence fonctionne avec du code Java sur Android. Votre IA se charge de lire la trace et d'effectuer les modifications de code.
Détails
Description originale de l’auteur
How to identify and fix Java memory leaks in Android Chrome using LeakCanary traces.
repo: chromium/chromium
Popularité
- Étoiles GitHub
- 25k
- Position au classement
- #10059
- Licence
- BSD-3-Clause
- Mis à jour
- 02/11/2026
Commentaires
- …
Autres skills de ce dépôt
fuzzing
25kAide votre agent à écrire des tests de fuzzing qui envoient de nombreuses entrées aléatoires au code pour trouver des plantages et des bugs dans le code C++.
gn-deps-debugging
25kAide votre agent à corriger les erreurs de compilation causées par des dépendances manquantes ou incorrectes dans les fichiers de compilation GN, sans ajouter de dépendances larges et inutiles.
jni-type-conversion
25kAide votre agent à remplacer le code manuel de conversion Java vers C++ par des annotations @JniType plus simples dans le code Android.
loadline
25kAide votre agent à lancer les benchmarks LoadLine, qui mesurent la vitesse de chargement des pages web sur Chrome Android et sur ordinateur.
Skills similaires
android-clean-architecture
280kPermet à votre agent d'organiser efficacement les projets Android. Il structure le code pour faciliter la maintenance et le développement de nouvelles fonctionnalités.
compose-multiplatform-patterns
280kAide votre agent à utiliser les patterns Compose Multiplatform et Jetpack Compose dans les projets KMP : état, navigation, thèmes et performances.
dart-flutter-patterns
280kPermet à votre agent d'écrire du code pour les applications Dart et Flutter. Il utilise des patterns modernes pour des apps robustes et faciles à gérer.