java management_Java ManagementFactory解析

作者: 一字马胡

转载标志 【2017-11-14】

更新日志

日期

更新内容

备注

2017-11-14

新建文章

初版

导入

ManagementFactory是一个为我们提供各种获取JVM信息的工厂类,使用ManagementFactory可以获取大量的运行时JVM信息,比如JVM堆的使用情况,以及GC情况,线程信息等,通过这些数据项我们可以了解正在运行的JVM的情况,以便我们可以做出相应的调整。本文将基于ManagementFactory,介绍如何通过ManagementFactory获取一些运行时的JVM信息,下面首先展示了ManagementFactory的类图,可以看出它提供了大量的工厂方法,使得我们可以通过调用这些方法来获取运行时的相关Bean,通过这些Bean就可以获取到我们想要的数据:

5d854245051d

使用ManagementFactory

上文中展示的ManagementFactory类图直观的说明了ManagementFactory提供的一些方法,可以看出我们可以获取的内容很多,下面将挑选几个具有代表性的MXBean来作为使用示例。

线程:ThreadMXBean

首先,可以通过下面的方式来获取一个ThreadMXBean:

ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();

下面的图片展示了ThreadMXBean支持的查询方法:

5d854245051d

下面的代码展示了ThreadMXBean的使用方法,通过ThreadMXBean提供的方法,我们可以获取详细的运行时JVM内的线程信息:

private static Map collectThreadInfo() {

final ThreadMXBean threadBean = ManagementFactory.getThreadMXBean();

Map map = new LinkedHashMap();

map.put("jvm.thread.count", threadBean.getThreadCount());

map.put("jvm.thread.daemon.count", threadBean.getDaemonThreadCount());

map.put("jvm.thread.totalstarted.count", threadBean.getTotalStartedThreadCount());

ThreadInfo[] threadInfos = threadBean.getThreadInfo(threadBean.getAllThreadIds());

int newThreadCount = 0;

int runnableThreadCount = 0;

int blockedThreadCount = 0;

int waitThreadCount = 0;

int timeWaitThreadCount = 0;

int terminatedThreadCount = 0;

if (threadInfos != null) {

for (ThreadInfo threadInfo : threadInfos) {

if (threadInfo != null) {

switch (threadInfo.getThreadState()) {

case NEW:

newThreadCount++;

break;

case RUNNABLE:

runnableThreadCount++;

break;

case BLOCKED:

blockedThreadCount++;

break;

case WAITING:

waitThreadCount++;

break;

case TIMED_WAITING:

timeWaitThreadCount++;

break;

case TERMINATED:

terminatedThreadCount++;

break;

default:

break;

}

} else {

/*

* If a thread of a given ID is not alive or does not exist,

* the corresponding element in the returned array will,

* contain null,because is mut exist ,so the thread is terminated

*/

terminatedThreadCount++;

}

}

}

map.put("jvm.thread.new.count", newThreadCount);

map.put("jvm.thread.runnable.count", runnableThreadCount);

map.put("jvm.thread.blocked.count", blockedThreadCount);

map.put("jvm.thread.waiting.count", waitThreadCount);

map.put("jvm.thread.time_waiting.count", timeWaitThreadCount);

map.put("jvm.thread.terminated.count", terminatedThreadCount);

lon

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值