简体   繁体   中英

How to create a heap dump inside a Java app?

I want to create a Java Heap Dump Analyzer project for educational purposes. I preferred capturing the dump file inside my app instead of taking dump file as an argument. But I don't know how to do it.

I thought of running jmap -dump... command with Runtime by giving PID but I'm not sure if it's the proper way. Can you help me with it?

Use Dynamic Attach API .

You'll still need to specify a file name where to save the dump.

import com.sun.tools.attach.VirtualMachine;
import sun.tools.attach.HotSpotVirtualMachine;

import java.io.InputStream;

public class HeapDump {

    public static void main(String[] args) throws Exception {
        String pid = args[0];
        HotSpotVirtualMachine vm = (HotSpotVirtualMachine) VirtualMachine.attach(pid);

        try (InputStream in = vm.dumpHeap("/tmp/heapdump.hprof")) {
            byte[] buf = new byte[200];
            for (int bytes; (bytes = in.read(buf)) > 0; ) {
                System.out.write(buf, 0, bytes);
            }
        } finally {
            vm.detach();
        }
    }
}

If you want to avoid a reference to a sun. … sun. … class, here's the JMX API variant:

private static void dumpHeap(String pid, String targetFile) throws Exception {
    VirtualMachine vm = VirtualMachine.attach(pid);
    String connectorAddress = vm.startLocalManagementAgent();
    JMXConnector c = JMXConnectorFactory.connect(new JMXServiceURL(connectorAddress));
    MBeanServerConnection sc = c.getMBeanServerConnection();
    sc.invoke(ObjectName.getInstance("com.sun.management:type=HotSpotDiagnostic"),
        "dumpHeap",
        new Object[] { targetFile, true }, new String[]{ "java.lang.String", "boolean" });
}

The boolean argument corresponds to the “live” parameter, see also HotSpotDiagnosticMXBean.dumpHeap

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM