Skip to content

Instantly share code, notes, and snippets.

@rajeshpv
Created March 27, 2025 13:54
Show Gist options
  • Save rajeshpv/723c64e0802cc1f5007a125bee2b6558 to your computer and use it in GitHub Desktop.
Save rajeshpv/723c64e0802cc1f5007a125bee2b6558 to your computer and use it in GitHub Desktop.
jvm_stat

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:


πŸš€ Step-by-Step Guide

βœ… 1. Enable JVM Heap Monitoring

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.jar

This:

  • Sets max and initial heap size.
  • Logs garbage collection and heap stats to gc.log.

βœ… 2. Use jstat (Java Statistics Monitoring Tool)

Run jstat while your app is running:

jstat -gc <pid> 1000 10

Where:

  • <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

βœ… 3. Heap Dump (Optional – for full analysis)

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

βœ… 4. Compare Between Runs

You can:

  • Diff the gc.log files.
  • Use Eclipse MAT to open both heap dumps and visually compare.
  • Look at jstat outputs side-by-side for patterns (like growing Old Gen memory or GC frequency).

🧠 Pro Tip

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.txt

Repeat 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?

@rajeshpv
Copy link
Author

rajeshpv commented Apr 1, 2025

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment