Skip to content

Instantly share code, notes, and snippets.

@vaibhav-yb
Created July 13, 2023 08:52
Show Gist options
  • Save vaibhav-yb/7015d9813b0345b281ff065d70e2c60c to your computer and use it in GitHub Desktop.
Save vaibhav-yb/7015d9813b0345b281ff065d70e2c60c to your computer and use it in GitHub Desktop.
Java program with step by step instructions on how to generate a heap dump

Generating a Heap Dump in Java

1. Create a Java program with the following contents

import java.util.ArrayList;
import java.util.List;

public class GenarateHeapDump {
  public static void main(String[] args) {
    List<byte[]> list = new ArrayList<>();
    int index = 1;
    while (true) {
      // 1MB each loop, 1 x 1024 x 1024 = 1048576
      byte[] b = new byte[1048576];
      list.add(b);
      Runtime rt = Runtime.getRuntime();
      System.out.printf("[%d] free memory: %s%n", index++, rt.freeMemory());
    }
  }
}
  1. Compile the program
javac GenerateHeapDump.java
  1. Create a directory to store heap dump files

I prefer to do it this way to keep my files isolated and avoid confusion.

mkdir dumpFiles
  1. Run the program
java -XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=/home/username/dumpFiles Solution

The above command will generate a heap dump file in the directory /home/username/dumpFiles which will have a name java_pid<pid>.hprof

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