从JVM内部访问JMX

时间:2012-12-22 03:56:42

标签: java jvm jmx

是否可以从里面那个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帖子,所以欢迎任何有关改进等问题的提示。

1 个答案:

答案 0 :(得分:6)

您可以轻松地使用此代码获取平台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";
}