📄 threadmonitorclient.java
字号:
package book.jmx.examples;
import javax.management.*;
import javax.management.monitor.*;
import java.util.List;
public class ThreadMonitorClient {
private MBeanServer server = null;
private ObjectName threads = null;
private ObjectName monitor = null;
public void run() {
// Find an agent from this JVM. Null argument will
// return a list of all MBeanServer instances.
List list = MBeanServerFactory.findMBeanServer(null);
server = (MBeanServer)list.iterator().next();
try {
// register the MBean reporting thread count
threads = new ObjectName("Observable:type=Threads");
server.registerMBean(new ThreadMonitor(), threads);
// configure the monitor
GaugeMonitor threadMon = new GaugeMonitor();
threadMon.setObservedObject(threads);
threadMon.setObservedAttribute("ThreadCount");
threadMon.setGranularityPeriod(5 * 1000);
threadMon.setNotifyHigh(true);
threadMon.setThresholds(
new Integer(30), new Integer(20)
);
// register the monitor
monitor = new ObjectName("Monitor:type=Threads");
server.registerMBean(threadMon, monitor);
threadMon.start();
server.addNotificationListener(
monitor, new MonitorListener(), null, monitor
);
// test the monitor by creating 35 extra threads
for (int i = 0; i < 35; ++i) {
Thread thread = new Thread(new Runnable() {
public void run() {
try {
Thread.sleep(10000);
}
catch (Exception ignored) {}
}
});
thread.start();
}
} catch (JMException e) {
e.printStackTrace();
}
}
class MonitorListener implements NotificationListener {
public void handleNotification(Notification n,
Object handback) {
MonitorNotification notif = (MonitorNotification)n;
if (notif.getType().equals
(MonitorNotification.THRESHOLD_HIGH_VALUE_EXCEEDED)
) {
System.out.println(
"Warning, Thread count exceeds " +
notif.getTrigger()
);
System.out.println(
"Current Thread count = " +
notif.getDerivedGauge()
);
}
}
}
//
// Main method for the client. This will instantiate
// an agent in the JVM.
//
public static void main(String[] args) {
MBeanServer server =
MBeanServerFactory.createMBeanServer();
new ThreadMonitorClient().run();
}
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -