001    package railo.commons.surveillance;
002    
003    import java.io.IOException;
004    import java.lang.management.ManagementFactory;
005    
006    import javax.management.MBeanServer;
007    
008    import railo.commons.io.SystemUtil;
009    import railo.commons.io.res.Resource;
010    import railo.commons.io.res.type.file.FileResource;
011    
012    import com.sun.management.HotSpotDiagnosticMXBean;
013    
014    public class HeapDumper {
015            
016            /**
017             * Dumps the heap to the outputFile file in the same format as the hprof heap dump.
018             * If this method is called remotely from another process, the heap dump output is written to a file named outputFile on the machine where the target VM is running. If outputFile is a relative path, it is relative to the working directory where the target VM was started.
019             * @param res Resource to write the .hprof file.
020             * @param live  if true dump only live objects i.e. objects that are reachable from others
021             * @throws IOException 
022             */
023            public static void dumpTo(Resource res, boolean live) throws IOException {
024                    MBeanServer mbserver = ManagementFactory.getPlatformMBeanServer();
025                    HotSpotDiagnosticMXBean mxbean = ManagementFactory.newPlatformMXBeanProxy( mbserver, "com.sun.management:type=HotSpotDiagnostic", HotSpotDiagnosticMXBean.class );
026                    
027                    String path;
028                    Resource tmp=null;
029                    if(res instanceof FileResource) path=res.getAbsolutePath();
030                    else {
031                            tmp=SystemUtil.getTempFile("hprof",false);
032                            path=tmp.getAbsolutePath();
033                    }
034                    try{
035                            // it only 
036                            mxbean.dumpHeap(path, live);
037                    }
038                    finally{
039                            if(tmp!=null && tmp.exists()){
040                                    tmp.moveTo(res);
041                            }
042                    }
043                    
044            }
045    }