Created
March 27, 2025 13:54
-
-
Save rajeshpv/723c64e0802cc1f5007a125bee2b6558 to your computer and use it in GitHub Desktop.
Revisions
-
rajeshpv created this gist
Mar 27, 2025 .There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,81 @@ 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: ```bash 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: ```bash 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: ```bash 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: ```bash #!/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?