FileDocCategorySizeDatePackage
ResourceUsageAgent.javaAPI DocExample2700Wed Apr 20 15:16:20 BST 2005None

ResourceUsageAgent

public class ResourceUsageAgent extends Object

Fields Summary
Constructors Summary
Methods Summary
public static voidpremain(java.lang.String args, java.lang.instrument.Instrumentation inst)

        // This agent simply registers a shutdown hook to run when the VM exits
        Runtime.getRuntime().addShutdownHook(new Thread() {
                public void run() {
                    // This code runs when the VM exits
                    try {
                        // Decide where to send our output
                        PrintWriter out;
                        if (args != null && args.length() > 0) 
                            out = new PrintWriter(new FileWriter(args));
                        else
                            out = new PrintWriter(System.err);

                        // Use java.lang.management to query peak thread usage
                        ThreadMXBean tb = ManagementFactory.getThreadMXBean();
                        out.printf("Current thread count: %d%n",
                                   tb.getThreadCount());
                        out.printf("Peak thread count: %d%n",
                                   tb.getPeakThreadCount());

                        // Use java.lang.management to query peak memory usage
                        List<MemoryPoolMXBean> pools = 
                            ManagementFactory.getMemoryPoolMXBeans();
                        for(MemoryPoolMXBean pool: pools) {
                            MemoryUsage peak = pool.getPeakUsage();
                            out.printf("Peak %s memory used: %,d%n",
                                       pool.getName(), peak.getUsed());
                            out.printf("Peak %s memory reserved: %,d%n",
                                       pool.getName(), peak.getCommitted());
                        }

                        // Use the Instrumentation object passed to premain()
                        // to get a list of all classes that have been loaded
                        Class[] loaded = inst.getAllLoadedClasses();
                        out.println("Loaded classes:");
                        for(Class c : loaded) out.println(c.getName());

                        out.close();  // close and flush the output stream
                    }
                    catch(Throwable t) {
                        // Exceptions in shutdown hooks are ignored so
                        // we've got to print this out explicitly
                        System.err.println("Exception in agent: " + t);
                    }
                }
            });