Quy trình 4 bước:
1. Phát hiện — heap usage tăng liên tục qua GC cycle. Monitor qua Actuator /metrics, Prometheus, hoặc GC log.
2. Capture heap dump:
jmap -dump:live,format=b,file=heap.hprof <pid>
# hoặc auto khi OOM:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dump3. Phân tích:
- Eclipse MAT (free) — báo cáo "Leak Suspects" tự động chỉ thẳng class nghi vấn.
- JProfiler/YourKit (commercial).
- Tìm: retained heap lớn bất thường, object count tăng theo thời gian.
4. Common culprits:
- static HashMap/List không clear.
- Event listener không deregister.
- ThreadLocal không remove().
- Connection pool leak (không close).
- Cache không có eviction.
JFR (Java Flight Recorder) — bundled OpenJDK 11+, overhead <2%:
-XX:StartFlightRecording=duration=60s,filename=app.jfr
# hoặc runtime:
jcmd <pid> JFR.start duration=60s filename=app.jfrTrack allocation rate, GC behavior, thread contention. Mở bằng JDK Mission Control.
Fix: try-with-resources, WeakReference cho cache, @PreDestroy cleanup, Caffeine cache với expire.
A four-step workflow:
1. Detect — heap usage climbs across GC cycles. Monitor via Actuator /metrics, Prometheus, or GC logs.
2. Capture a heap dump:
jmap -dump:live,format=b,file=heap.hprof <pid>
# or auto on OOM:
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/dump3. Analyse:
- Eclipse MAT (free) — "Leak Suspects" report points straight at the culprit.
- JProfiler/YourKit (commercial).
- Look for: abnormally large retained heap, object counts growing over time.
4. Common culprits:
- static HashMap/List never cleared.
- Event listeners not deregistered.
- ThreadLocal not remove()-d.
- Connection pool leaks (not closed).
- Caches without eviction.
JFR (Java Flight Recorder) — bundled with OpenJDK 11+, <2% overhead:
-XX:StartFlightRecording=duration=60s,filename=app.jfr
# or at runtime:
jcmd <pid> JFR.start duration=60s filename=app.jfrTracks allocation rate, GC behaviour, thread contention. Open with JDK Mission Control.
Fix: try-with-resources, WeakReference for caches, @PreDestroy cleanup, Caffeine cache with expiry.