Java heap dumps

Posted by Mike Haller on Monday, November 24. 2008 at 10:00 in Java
For analysis of memory leaks in Java applications, the heap dump is an essential source of information which is quite helpful. The dump files can be analyzed with tools like Eclipse Memory Analyzer Tool.

To get a heap dump, there are multiple ways. The first, which should be enabled in all circumstances and especially on production systems, is by adding a VM option. By enabling -XX:+HeapDumpOnOutOfMemory, a heap dump is automatically written to disk when OutOfMemoryErrors occur.

The second way is to manually force a heap dump at runtime at any point of time, without the need of an actual OutOfMemoryError. For this to work, you need to enable Java Management Extensions. Enable JMX by adding the following system properties to your launch configuration of Tomcat:


-Dcom.sun.management.jmxremote
-Dcom.sun.management.jmxremote.port="9004"
-Dcom.sun.management.jmxremote.authenticate="false"
-Dcom.sun.management.jmxremote.ssl="false"


Now run the following code to get a dump of the heap at runtime:

String url = "service:jmx:rmi:///jndi/rmi://localhost:9004/jmxrmi";
JMXServiceURL jmxURL = new JMXServiceURL(url);
JMXConnector connector = JMXConnectorFactory.connect(jmxURL);
MBeanServerConnection connection = connector.getMBeanServerConnection();
String hotSpotDiagName = "com.sun.management:type=HotSpotDiagnostic";
ObjectName name = new ObjectName(hotSpotDiagName);
String operationName = "dumpHeap";
File tempFile = File.createTempFile("heapdump", ".hprof");
tempFile.delete();
String dumpFilename = tempFile.getAbsolutePath();
Object[] params = new Object[] { dumpFilename, Boolean.TRUE };
String[] signature = new String[] { String.class.getName(), boolean.class.getName() };
Object result = connection.invoke(name, operationName, params, signature);
System.out.println("Dumped to " + dumpFilename);



Add Comment

Enclosing asterisks marks text as bold (*word*), underscore are made via _word_.
Standard emoticons like :-) and ;-) are converted to images.
E-Mail addresses will not be displayed and will only be used for E-Mail notifications
 
Submitted comments will be subject to moderation before being displayed.
 

About

My name is Mike Haller and I'm a software developer and architect at Innovations Software Technology in Germany. I love programming, playing games and reading books. I like good food, making photos and learning and mentoring about the craftsmanship of commercial software development.

Quicksearch