gpt4 book ai didi

java - 从 JVM 内部访问 JMX

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:25:45 25 4
gpt4 key购买 nike

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

+----------------------------------------+   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";
}

关于java - 从 JVM 内部访问 JMX,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13999922/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com