Middle
The service is crashing with OutOfMemoryError in production. How to localize the problem?
sobes.tech AI
Answer from AI
For localizing OutOfMemoryError in production:
-
Collect a heap dump at the moment of failure or immediately after the error occurs. This can be done using JVM parameters (
-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/path/to/dump) or tools likejmap. -
Analyze the heap dump using profilers (e.g., Eclipse MAT, VisualVM). Look for:
- Objects occupying a lot of memory.
- Memory leaks — objects that should not live that long.
-
Check logs and metrics:
- Use monitoring (e.g., Prometheus, Grafana) to track memory consumption over time.
- See if memory usage gradually increases (memory leak) or suddenly.
-
Check JVM settings:
- Heap size (
-Xmx,-Xms), garbage collector parameters. - Consider increasing memory or optimizing GC.
- Heap size (
-
Review the code:
- Look for large collections that are not cleared.
- Pay special attention to caches, singletons, static fields.
-
Test locally with load to reproduce the problem and verify hypotheses.
Example command to manually create a heap dump:
jmap -dump:format=b,file=heapdump.hprof <pid>
Analyzing the dump in Eclipse MAT can help identify "Leak Suspects" — objects that retain memory.