Monday, 7 October 2019

Java: Generate heap dump programmatically


Step 1: Get the hotspot diagnostic MBean from the platform MBean server.

MBeanServer server = ManagementFactory.getPlatformMBeanServer();
HotSpotDiagnosticMXBean hotspotMBean = ManagementFactory.newPlatformMXBeanProxy(server, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class);


Step 2: Use dumpHeap method of HotSpotDiagnosticMXBean to generate heap dump.

void dumpHeap(String outputFile, boolean live)
Dumps the heap to the outputFile file in the same format as the hprof heap dump. If the parameter 'live' is set to then this method dump only live objects i.e. objects that are reachable from others

Example
hotspotMBean.dumpHeap(fileName, true);

Find the below working application.

HeapDumpUtil.java
package com.sample.app.util;

import java.io.IOException;
import java.lang.management.ManagementFactory;

import javax.management.MBeanServer;

import com.sun.management.HotSpotDiagnosticMXBean;

public class HeapDumpUtil {
 private static final String HOTSPOT_BEAN_NAME = "com.sun.management:type=HotSpotDiagnostic";

 private static HotSpotDiagnosticMXBean hotspotMBean = null;

 /* Get the hotspot diagnostic MBean from the platform MBean server */
 private static HotSpotDiagnosticMXBean getHotspotMBean() throws IOException {
  MBeanServer server = ManagementFactory.getPlatformMBeanServer();
  return ManagementFactory.newPlatformMXBeanProxy(server, HOTSPOT_BEAN_NAME, HotSpotDiagnosticMXBean.class);

 }

 public static void generateHeapDump(String fileName) throws IOException {
  if (hotspotMBean == null) {
   synchronized (HeapDumpUtil.class) {
    if (hotspotMBean == null) {
     hotspotMBean = getHotspotMBean();
    }
   }
  }

  hotspotMBean.dumpHeap(fileName, true);
 }

}


App.java
package com.sample.app;

import java.io.IOException;

import com.sample.app.util.HeapDumpUtil;

public class App {

 public static void main(String args[]) throws IOException  {
  HeapDumpUtil.generateHeapDump("dump1.hprof");
 }
}

You may like

jstat: Monitor Java heap, threads, classes


Previous                                                    Next                                                    Home

No comments:

Post a Comment