Taking Java heap dump programmatically

The following code snippet can be used to take heap dump of Java program programmatically.

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

import javax.management.MBeanServer;

import com.sun.management.HotSpotDiagnosticMXBean;

public abstract class HeapDumper {

    private static final HotSpotDiagnosticMXBean HOT_SPOT_DIAGNOSTIC_MX_BEAN = getHotspotDiagnosticMxBean();
    private static final String HOTSPOT_BEAN_NAME = "com.sun.management:type=HotSpotDiagnostic";

    private static HotSpotDiagnosticMXBean getHotspotDiagnosticMxBean() {
        MBeanServer server = ManagementFactory.getPlatformMBeanServer();
        try {
            return ManagementFactory.newPlatformMXBeanProxy(
                    server, HOTSPOT_BEAN_NAME, HotSpotDiagnosticMXBean.class);
        } catch (IOException error) {
            throw new RuntimeException("failed getting Hotspot Diagnostic MX bean", error);
        }
    }

    public static void createHeapDump(File file, boolean live) {
        try {
            HOT_SPOT_DIAGNOSTIC_MX_BEAN.dumpHeap(file.getAbsolutePath(), live);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}