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 spacesEC,EU– Eden space capacity and usedOC,OU– Old gen capacity and usedYGC,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?
Analyzing
.hproffiles (Java Heap Profile files) in Java 17 can help you troubleshoot memory leaks, check object allocations, or understand memory usage. Here’s how to do it:🔧 Tools You Can Use (Java 17 Compatible):
1. JDK's
jhat(deprecated in Java 9+)Not available in Java 17, so skip unless you're using an older JDK.
2. Eclipse Memory Analyzer (MAT) – 💯 Most common
Download: [MAT from Eclipse](https://www.eclipse.org/mat/downloads.php)
Usage:
.hproffile.Great for:
3. JVisualVM
.hproffile from File → Load.4.
jhsdb(Java HotSpot Debugger)Comes with JDK 17. Command-line tool.
Run it like this:
Or:
Good for detailed debugging, but less user-friendly.
5. Other Third-Party Tools:
🧠 What You Can Analyze in
.hprof:🧪 Pro Tips:
java.util.HashMap,byte[], etc.).OQL(Object Query Language) in MAT to write SQL-like queries on heap.Need help with a specific
.hproffile? I can guide you through interpreting it.