java – 从JVM内部访问JMX

前端之家收集整理的这篇文章主要介绍了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帖子,所以欢迎任何有关改进等问题的提示.

解决方法

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

猜你在找的JVM相关文章