public void monitor int vmpid throws Exception JMXServiceURL url new J

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
public void monitor(int vmpid) throws Exception {
JMXServiceURL url = new JMXServiceURL(getVMAddress(vmpid));
JMXConnector connector = JMXConnectorFactory.connect(url);
final MBeanServerConnection serverConnection = connector.getMBeanServerConnection();
Set<ObjectName> beanSet = serverConnection.queryNames(new ObjectName("java.lang:type=GarbageCollector,name=PS MarkSweep"), null);
final ObjectName bean = beanSet.iterator().next();
GarbageCollectorMXBean gcBean = JMX.newMXBeanProxy(serverConnection,bean, GarbageCollectorMXBean.class);
System.out.println("collection time: " + gcBean.getCollectionTime());
System.out.println("collection count: " + gcBean.getCollectionCount());
GcInfo gcInfo = gcBean.getLastGcInfo();
Map<String, MemoryUsage> memUsages = gcInfo.getMemoryUsageBeforeGc();
for (Entry<String, MemoryUsage> memUsage : memUsages.entrySet()) {
System.out.println(memUsage.getKey() + ": " + memUsage.getValue());
}
listenToNotifications(serverConnection, bean);
}
private String getVMAddress(int pid) throws AttachNotSupportedException, IOException {
String jmxAddressProp = "com.sun.management.jmxremote.localConnectorAddress";
VirtualMachine vm = VirtualMachine.attach(String.valueOf(pid));
return vm.getAgentProperties().getProperty(jmxAddressProp);
}