Sun JVM上的CPU使用率(%)MBean

tul*_*ler 11 jvm cpu-usage

jconsole上进程的概述选项卡显示了CPU使用率百分比.有没有MBean给我这个价值?它的ObjectName是什么?

isa*_*pir 18

更新:在Java 7中,您可以这样做:

public static double getProcessCpuLoad() throws MalformedObjectNameException, ReflectionException, InstanceNotFoundException {

    MBeanServer mbs    = ManagementFactory.getPlatformMBeanServer();
    ObjectName name    = ObjectName.getInstance("java.lang:type=OperatingSystem");
    AttributeList list = mbs.getAttributes(name, new String[]{ "ProcessCpuLoad" });

    if (list.isEmpty())     return Double.NaN;

    Attribute att = (Attribute)list.get(0);
    Double value  = (Double)att.getValue();

    if (value == -1.0)      return Double.NaN;

    return ((int)(value * 1000) / 10.0);        // returns a percentage value with 1 decimal point precision
}
Run Code Online (Sandbox Code Playgroud)

-----以下原始答案-----

在Java 7中,您可以使用以下隐藏方法com.sun.management.OperatingSystemMXBean:

getProcessCpuLoad()    // returns the CPU usage of the JVM

getSystemCpuLoad()     // returns the CPU usage of the whole system
Run Code Online (Sandbox Code Playgroud)

这两个值都以0.0和1.0之间的双精度返回,因此只需乘以100即可获得百分比.

com.sun.management.OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);
System.out.println(osBean.getProcessCpuLoad() * 100);
System.out.println(osBean.getSystemCpuLoad()  * 100);
Run Code Online (Sandbox Code Playgroud)

由于这些是隐藏的,未记录的,因此存在于com.sun.management.OperatingSystemMXBean包中而不存在于其中的方法存在在java.lang.management.OperatingSystemMXBean某些JVM或将来的更新中不可用的风险,因此您应该决定是否愿意承担该风险.

请参阅https://www.java.net/community-item/hidden-java-7-features-%E2%80%93-system-and-process-cpu-load-monitoring了解更多信息.


Jos*_*seK 2

ManagementFactory 中似乎没有直接的 MBean。最接近的是http://java.sun.com/javase/6/docs/api/java/lang/management/OperatingSystemMXBean.html#getSystemLoadAverage(),它可用于计算整个系统使用的CPU。

然而这个URL建议了一种基于jconsole源代码的方法