001/*
002 * (C) Copyright 2011 Nuxeo SA (http://nuxeo.com/) and contributors.
003 *
004 * All rights reserved. This program and the accompanying materials
005 * are made available under the terms of the GNU Lesser General Public License
006 * (LGPL) version 2.1 which accompanies this distribution, and is available at
007 * http://www.gnu.org/licenses/lgpl.html
008 *
009 * This library is distributed in the hope that it will be useful,
010 * but WITHOUT ANY WARRANTY; without even the implied warranty of
011 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
012 * Lesser General Public License for more details.
013 *
014 * Contributors:
015 *     matic
016 */
017package org.nuxeo.runtime.management.jvm;
018
019import java.io.File;
020import java.io.IOException;
021import java.lang.management.ManagementFactory;
022
023import javax.management.MBeanServer;
024
025import com.sun.management.HotSpotDiagnosticMXBean;
026
027/**
028 * Helper to dump the heap in a temporary file.
029 *
030 * @author matic
031 * @since 5.5
032 */
033public class HeapDumper {
034
035    private static final String HOTSPOT_NAME = "com.sun.management:type=HotSpotDiagnostic";
036
037    public HeapDumper() throws IOException {
038    }
039
040    protected final HotSpotDiagnosticMXBean diag = newDiag();
041
042    protected HotSpotDiagnosticMXBean newDiag() throws IOException {
043        MBeanServer mbs = ManagementFactory.getPlatformMBeanServer();
044        return ManagementFactory.newPlatformMXBeanProxy(mbs, HOTSPOT_NAME, HotSpotDiagnosticMXBean.class);
045    }
046
047    /**
048     * Dumps heap in a temporary file and returns the file
049     *
050     * @since 5.5
051     * @throws IOException
052     */
053    public File dumpHeap() throws IOException {
054        File file = File.createTempFile("heapdump", ".hprof");
055        file.delete();
056        newDiag().dumpHeap(file.getAbsolutePath(), true);
057        return file;
058    }
059
060}