Last active
August 29, 2015 14:01
-
-
Save hanbei/9a94ec05a3f112beebe3 to your computer and use it in GitHub Desktop.
HeapDumper
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import com.sun.management.HotSpotDiagnosticMXBean; | |
import java.lang.management.ManagementFactory; | |
import javax.management.MBeanServer; | |
public class HeapDumper { | |
// This is the name of the HotSpot Diagnostic MBean | |
private static final String HOTSPOT_BEAN_NAME = "com.sun.management:type=HotSpotDiagnostic"; | |
// field to store the hotspot diagnostic MBean | |
private static volatile HotSpotDiagnosticMXBean hotspotMBean; | |
public static void dumpHeap(String fileName, boolean live) { | |
// initialize hotspot diagnostic MBean | |
initHotspotMBean(); | |
try { | |
hotspotMBean.dumpHeap(fileName, live); | |
} | |
catch(RuntimeException re) { | |
throw re; | |
} | |
catch(Exception exp) { | |
throw new RuntimeException(exp); | |
} | |
} | |
// initialize the hotspot diagnostic MBean field | |
private static void initHotspotMBean() { | |
if (hotspotMBean == null) { | |
synchronized (HeapDumper.class) { | |
if (hotspotMBean == null) { | |
hotspotMBean = getHotspotMBean(); | |
} | |
} | |
} | |
} | |
// get the hotspot diagnostic MBean from the | |
// platform MBean server | |
private static HotSpotDiagnosticMXBean getHotspotMBean() { | |
try { | |
MBeanServer server = ManagementFactory.getPlatformMBeanServer(); | |
HotSpotDiagnosticMXBean bean = | |
ManagementFactory.newPlatformMXBeanProxy(server, | |
HOTSPOT_BEAN_NAME, HotSpotDiagnosticMXBean.class); | |
return bean; | |
} | |
catch(RuntimeException re) { | |
throw re; | |
} | |
catch(Exception exp) { | |
throw new RuntimeException(exp); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment