Capturing JVM heap allocation and comparing it between two executions of a Java application can be super insightful when you're analyzing memory usage, leaks, or performance. Hereβs a practical way to do it:
Use the following Java options when running your app to capture memory usage:
java -Xmx512m -Xms512m -XX:+PrintGCDetails -XX:+PrintGCDateStamps -Xloggc:gc.log -jar your-app.jarThis:
- Sets max and initial heap size.
- Logs garbage collection and heap stats to gc.log.
Run jstat while your app is running:
jstat -gc <pid> 1000 10Where:
- <pid>= Process ID of the Java app.
- 1000= delay between samples (in ms).
- 10= number of samples.
This gives heap usage stats like:
- S0C,- S1Cβ survivor spaces
- EC,- EUβ Eden space capacity and used
- OC,- OUβ Old gen capacity and used
- YGC,- FGCβ young/full GC counts
Capture a heap dump:
jmap -dump:format=b,file=heap1.hprof <pid>Do this at both execution points (heap1.hprof and heap2.hprof).
You can analyze .hprof files using tools like:
- Eclipse MAT (Memory Analyzer Tool)
- VisualVM
- JProfiler
You can:
- Diff the gc.logfiles.
- Use Eclipse MAT to open both heap dumps and visually compare.
- Look at jstatoutputs side-by-side for patterns (like growing Old Gen memory or GC frequency).
Automate it via a shell script:
#!/bin/bash
java -Xmx512m -Xms512m -Xloggc:gc_run1.log -jar your-app.jar
# then:
jstat -gc <pid> > jstat_run1.txtRepeat for run2 and then use diff or Excel to compare jstat_run1.txt and jstat_run2.txt.
Want help writing a script to automate all this? Or comparing .hprof files with MAT?
https://visualvm.github.io/download.html