1 36 37 40 41 import static java.lang.management.ManagementFactory .*; 42 import java.lang.management.*; 43 import javax.management.*; 44 import java.io.*; 45 import java.util.*; 46 47 54 public class PrintGCStat { 55 private RuntimeMXBean rmbean; 56 private MemoryMXBean mmbean; 57 private List<MemoryPoolMXBean> pools; 58 private List<GarbageCollectorMXBean> gcmbeans; 59 60 63 public PrintGCStat(MBeanServerConnection server) throws IOException { 64 this.rmbean = newPlatformMXBeanProxy(server, 66 RUNTIME_MXBEAN_NAME, 67 RuntimeMXBean.class); 68 this.mmbean = newPlatformMXBeanProxy(server, 69 MEMORY_MXBEAN_NAME, 70 MemoryMXBean.class); 71 ObjectName poolName = null; 72 ObjectName gcName = null; 73 try { 74 poolName = new ObjectName(MEMORY_POOL_MXBEAN_DOMAIN_TYPE+",*"); 75 gcName = new ObjectName(GARBAGE_COLLECTOR_MXBEAN_DOMAIN_TYPE+",*"); 76 } catch (MalformedObjectNameException e) { 77 assert(false); 79 } 80 81 Set mbeans = server.queryNames(poolName, null); 82 if (mbeans != null) { 83 pools = new ArrayList<MemoryPoolMXBean>(); 84 Iterator iterator = mbeans.iterator(); 85 while (iterator.hasNext()) { 86 ObjectName objName = (ObjectName) iterator.next(); 87 MemoryPoolMXBean p = 88 newPlatformMXBeanProxy(server, 89 objName.getCanonicalName(), 90 MemoryPoolMXBean.class); 91 pools.add(p); 92 } 93 } 94 95 mbeans = server.queryNames(gcName, null); 96 if (mbeans != null) { 97 gcmbeans = new ArrayList<GarbageCollectorMXBean>(); 98 Iterator iterator = mbeans.iterator(); 99 while (iterator.hasNext()) { 100 ObjectName objName = (ObjectName) iterator.next(); 101 GarbageCollectorMXBean gc = 102 newPlatformMXBeanProxy(server, 103 objName.getCanonicalName(), 104 GarbageCollectorMXBean.class); 105 gcmbeans.add(gc); 106 } 107 } 108 } 109 110 113 public PrintGCStat() { 114 this.rmbean = getRuntimeMXBean(); 116 this.mmbean = getMemoryMXBean(); 117 this.pools = getMemoryPoolMXBeans(); 118 this.gcmbeans = getGarbageCollectorMXBeans(); 119 } 120 121 125 public void printVerboseGc() { 126 System.out.print("Uptime: " + formatMillis(rmbean.getUptime())); 127 for (GarbageCollectorMXBean gc : gcmbeans) { 128 System.out.print(" [" + gc.getName() + ": "); 129 System.out.print("Count=" + gc.getCollectionCount()); 130 System.out.print(" GCTime=" + formatMillis(gc.getCollectionTime())); 131 System.out.print("]"); 132 } 133 System.out.println(); 134 for (MemoryPoolMXBean p : pools) { 135 System.out.print(" [" + p.getName() + ":"); 136 MemoryUsage u = p.getUsage(); 137 System.out.print(" Used=" + formatBytes(u.getUsed())); 138 System.out.print(" Committed=" + formatBytes(u.getCommitted())); 139 System.out.println("]"); 140 } 141 } 142 143 private String formatMillis(long ms) { 144 return String.format("%.4fsec", ms / (double) 1000); 145 } 146 private String formatBytes(long bytes) { 147 long kb = bytes; 148 if (bytes > 0) { 149 kb = bytes / 1024; 150 } 151 return kb + "K"; 152 } 153 } 154 | Popular Tags |