javajvmheap-dumpjvm-crash

How to take heap dump?


I want to collect heap dump on JVM crash

So i wrote a simple code

public class Test {
private String name;

public Test(String name) {
    this.name = name;
}

public void execute() {

    Map<String,String> randomData = new HashMap<String,String>();
    for(int i=0;i<1000000000;i++) {
       randomData.put("Key:" + i,"Value:" + i);
    }
}

public void addData() {
}

public static void main(String args[]) {
    String myName = "Aniket";
    Test tStart = new Test(myName);
    tStart.execute();
}
}

and I am running it as follows

[aniket@localhost Desktop]$ java -cp . -Xms2m -Xmx2m Test
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
    at Test.execute(Test.java:15)
    at Test.main(Test.java:25)

I got OutOfMemoryError which I wanted but there is no heap dump in the working directory(like hs_err_pidXXXX.log which I expected). What am I missing? How do I get a heap dump?

Update :

I tried -XX:ErrorFile=. still no use. If above is not the way to get the heap dump(Crash JVM) how can I crash my JVM to get those logs?


Solution

  • You are confusing an exception or error being thrown as a JVM crash.

    A JVM crash occurs due to an internal error in the JVM, you cannot trigger this by writing a normal Java program (or should not unless you find a bug)

    What you are doing is triggering an Error which means the program continues to run until all the non daemon threads exit.

    The simplest tool to examine the heap is VisualVM which comes with the JDK. If you want to trigger a heap dump on an OutOfMemoryError you can use -XX:+HeapDumpOnOutOfMemoryError