java-memory-leaks
Что он делает
Этот скилл ведёт ИИ к поиску причины, по которой приложение для Android удерживает память, которую должно освободить. Он нужен разработчикам Android, которые видят отчёты об утечках в тестах.
Когда использовать
- ✓Когда в логе теста есть отчёт LeakCanary об утечке памяти.
- ✓Когда экран или компонент Android как будто остаётся в памяти после закрытия.
- ✓Когда нужно прочитать трассировку утечки и найти объект, который должен быть очищен.
Ссылка на скилл
https://github.com/chromium/chromium/blob/main/agents/skills/java-memory-leaks/SKILL.mdСкопируйте и вставьте её в ваш ИИ (Claude, ChatGPT или Cursor) с просьбой следовать инструкциям.
Как использовать
Самый простой способ: скопируйте сообщение и вставьте его в свой ИИ. Он прочитает скилл и выполнит инструкции.
Готовое сообщение для вставки
Для Claude Code, Codex или Cursor: запустите в папке проекта, и скилл установится.
Скачайте SKILL.md и положите его в папку скиллов вашего агента.
Пример запроса к вашему ИИ
“Мой тест Android показывает утечку LeakCanary. Можешь прочитать трассировку и помочь её исправить?”
5 новых скиллов в неделю. 1 минута чтения.
Как это работает
ИИ подтверждает утечку, запустив тест, читает трассировку от корня до утекающего объекта, находит ссылку, которую нужно очистить, и предлагает исправление.
Технический текст (оригинальный SKILL.md)
Оригинальный текст автора на английском, прямо с 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
Частые вопросы
Что такое утечка памяти?
Утечка памяти возникает, когда приложение держит в памяти объекты, которые уже не нужны. Со временем это может замедлить приложение или привести к падению.
Что такое LeakCanary?
LeakCanary — инструмент, который находит утечки памяти в приложениях Android и пишет трассировку, показывающую, что удерживает объект.
Нужно ли знать Java для этого?
Да, скилл работает с кодом Java для Android. ИИ читает трассировку и вносит изменения в код.
Подробности
Оригинальное описание автора
How to identify and fix Java memory leaks in Android Chrome using LeakCanary traces.
repo: chromium/chromium
Популярность
- Звёзды на GitHub
- 25k
- Место в рейтинге
- #10059
- Лицензия
- BSD-3-Clause
- Обновлён
- 02.11.2026
Комментарии
- …
Другие скиллы из этого репозитория
fuzzing
25kПомогает агенту писать фаззинг-тесты, которые подают в код много случайных входных данных, чтобы найти падения и ошибки в C++-коде.
gn-deps-debugging
25kПомогает агенту исправлять ошибки сборки из-за отсутствующих или неверных зависимостей в файлах сборки GN, не добавляя широких и ненужных зависимостей.
jni-type-conversion
25kПомогает агенту заменить ручной код преобразования из Java в C++ более простыми аннотациями @JniType в коде для Android.
loadline
25kПомогает агенту запускать бенчмарки LoadLine, которые измеряют, как быстро загружаются веб-страницы в Chrome на Android и в десктопной версии.
Похожие скиллы
android-clean-architecture
280kПомогает агенту эффективно организовывать Android-проекты. Структурирует код, чтобы его было проще поддерживать и развивать.
compose-multiplatform-patterns
280kПомогает агенту применять паттерны Compose Multiplatform и Jetpack Compose в KMP-проектах: состояние, навигация, темы и производительность.
dart-flutter-patterns
280kАгент пишет код для приложений на Dart и Flutter по современным паттернам, чтобы они были надёжными и управляемыми.