Sub topic 3
Reading GC Logs and Diagnosing JVM Memory Problems
Assume you know basic Java syntax, references, and how to run a Java program from the command line. This chapter uses Java 11 and its unified logging system.
Reading GC logs
Enable garbage-collection (GC) logging with -Xlog:
java -Xms512m -Xmx512m -Xlog:gc*:file=gc.log:time,uptime,level,tags MyAppThe log records when collections start, which collector runs, and how much memory remains afterward. A line such as 200M->40M(512M) means that used heap changed from 200 MB to 40 MB, with a 512 MB maximum heap.
Look for these patterns:
- Frequent collections with little memory reclaimed can indicate a leak or a heap that is too small.
- Long pause times can indicate large collections or allocation pressure.
- Old-generation collections are usually more expensive than young-generation collections.
- A steadily rising post-GC occupancy is a warning sign.
Heap sizing and basic tuning
-Xms sets the initial heap size. -Xmx sets the maximum heap size. A fixed heap can make behavior more predictable:
java -Xms512m -Xmx512m -XX:+UseG1GC -Xlog:gc*:file=gc.log MyAppDo not increase -Xmx automatically. A larger heap may reduce collection frequency but can increase collection work and leave less memory for the operating system or native allocations.
Understanding `OutOfMemoryError`
The message identifies the exhausted area:
| Message | Typical cause |
|---|---|
| `Java heap space` | Too many reachable objects or insufficient heap |
| `Metaspace` | Too much class metadata, often from class-loader leaks |
| `Direct buffer memory` | Excessive off-heap buffers |
| `GC overhead limit exceeded` | The JVM spends most of its time collecting with little progress |
A memory leak is possible even in a garbage-collected program. A static collection, listener, cache, or thread-local can keep unwanted objects reachable from a GC root.
> callout note > Treat System.gc() as a request only. It does not guarantee that a collection will occur.
Diagnosing memory problems
Request a heap dump when an out-of-memory error occurs:
java -Xmx256m -XX:+HeapDumpOnOutOfMemoryError \
-XX:HeapDumpPath=./dumps MyAppFor a running process, use its process ID with jcmd:
jcmd <pid> GC.heap_info
jcmd <pid> GC.class_histogramA heap dump shows retained objects and their reference paths. Java Flight Recorder (JFR) adds time-based evidence, including allocation activity, pauses, and CPU use.
Exercise
What does 200M->40M(512M) mean in a GC log?
Show answer
Used heap fell from 200 MB to 40 MB after collection, and the maximum heap is 512 MB.