7

是否可以从该 JVM 实例内部访问 JVM 的 JMX 服务器?还是我必须通过标准套接字/端口远程接口连接?

+----------------------------------------+   Option 2: Connect
|       +---------------------------+    |   through sockets like
|       | My Notification Listener  |+----->----------+ a remote
|       |                           |    |            | monitor.
|       +---------------------------+    |            |
|                           +            |            |
|          Option 1: connect|            |            |
|          to the internal  |            |            |
|          JMX server. I'm  |            |            |
|          trying to find   |            |            |
|          if this is possible.          |            |
|                           |            |            |
|                           |            |            |
|    A single JVM instance. |            |            |
|                           |            |            |
|        +------------+-----v------+--+  |            |
|        |            | GuageMXBean|<-+<--------------+
|        |            +------------+  |  |
|        | JMX MXBean Server          |  |
|        +----------------------------+  |
+----------------------------------------+

背景:我正在尝试实现一个响应 JVM 状态的“智能”系统,特别是内存使用情况,在将工作数据缓存到磁盘和将其保存在 ram 之间切换。设置 JMX 侦听器似乎比运行执行以下操作的后台线程更优雅:

Runtime RTime = Runtime.getRuntime();
while(!shutdown)
{
    if((RTime.totalMemory / RTime.maxMemory) > upperThreshold) cachmode = CACHETODISK;
    if((RTime.totalMemory / RTime.maxMemory) < lowerThreshold) cachmode = CACHETORAM;
    Sleep(1000);
}

桌面应用程序,如果它有所作为。

这是我的第一篇 SO 帖子,因此欢迎任何关于改进等问题的提示。

4

1 回答 1

7

您可以使用此代码轻松获取平台 MBean Server。

ManagementFactory.getPlatformMBeanServer();

有很多有用的 MBean 可用于收集有关 JVM 状态的信息。这是一个简单的例子

List<GarbageCollectorMXBean> gcBeans = ManagementFactory.getGarbageCollectorMXBeans(); 

// generate heap state report 
String report = "";     
for (GarbageCollectorMXBean gc : gcBeans) {
    report += "\nGC Name         : " + gc.getName();
    report += "\nCollection count: " + gc.getCollectionCount();
    report += "\nCollection Time : " + gc.getCollectionTime() + " milli seconds";
    report += "\n";
}       

List<MemoryPoolMXBean> memoryPoolMXBeans = ManagementFactory.getMemoryPoolMXBeans();
for (MemoryPoolMXBean pool : memoryPoolMXBeans) {
    report += "\nMemory Pool: " + pool.getName();
    MemoryUsage usage = pool.getUsage();
    report += "\n   Max : " + usage.getMax() / 1024000 + "MB"; 
    report += "\n   Used: " + usage.getUsed() / 1024000 + "MB";
    report += "\n";
}
于 2012-12-22T04:54:47.270 回答