2008-08-04

Servlet to create java heap dumps

To create a heap dump for analyzing memory usage one needs to use non-portable API:s. This is example code using suns HotSpotDiagnosticMXBean, but using reflection to avoid compile-time dependency on the sun class library:
public class HeapDumpServlet extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
File tmpFile = File.createTempFile("heapdump", ".hprof");
try {
MBeanServer server = ManagementFactory.getPlatformMBeanServer();
// use reflection to avoid compile time dependency on sun classes
String className = "com.sun.management.HotSpotDiagnosticMXBean";
Class diagClass = Class.forName(className);
Object diagBean = ManagementFactory.newPlatformMXBeanProxy(server,
"com.sun.management:type=HotSpotDiagnostic", diagClass);
Method dumpHeapMethod = diagClass.getMethod("dumpHeap", String.class, boolean.class);
dumpHeapMethod.invoke(diagBean, tmpFile.getAbsolutePath(), true);
response.setContentType("application/octet-stream");
response.addHeader("Content-Disposition", "attachment; filename=heapdump.hprof");
IOUtils.copy(new FileInputStream(tmpFile), response.getOutputStream());
} catch (Exception e) {
response.setContentType("text/plain");
response.getWriter().println("ERROR: " + e.getMessage() + "\n" + ExceptionUtils.getFullStackTrace(e));
} finally {
tmpFile.delete();
}
}

}

No comments: