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

时间:2010-06-15 11:54:08

标签: jvm cpu-usage

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

4 个答案:

答案 0 :(得分: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
}

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

在Java 7中,您可以使用com.sun.management.OperatingSystemMXBean

的隐藏方法
getProcessCpuLoad()    // returns the CPU usage of the JVM

getSystemCpuLoad()     // returns the CPU usage of the whole system

两个值都以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);

由于这些是隐藏的,未记录的,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了解更多信息。

答案 1 :(得分:1)

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

然而this URL has suggested a method基于jconsole的源代码

答案 2 :(得分:0)

我修改了互联网上的代码,就像这样,然后我测试了它,结果几乎与linux ps命令的结果相符。

/ **下面是代码* /

public float getCpuUsed() {

    /** get a MXBean  */
    com.sun.management.OperatingSystemMXBean osMXBean =
    (com.sun.management.OperatingSystemMXBean) 
    ManagementFactory.getOperatingSystemMXBean();


    /** set old timestamp values */
    long previousJvmProcessCpuTime = osMXBean.getProcessCpuTime();


    int sleepTime = 350;
    /** sleep for a while to use to calculate */
    try {
        TimeUnit.MILLISECONDS.sleep(sleepTime);
    } catch (InterruptedException e) {
        logger.error("InterruptedException occurred while MemoryCollector sleeping...");
    }

    /** elapsed process time is in nanoseconds */
    long elapsedProcessCpuTime = osMXBean.getProcessCpuTime() - previousJvmProcessCpuTime;

    /** elapsed uptime is in milliseconds */

    long elapsedJvmUptime = sleepTime ;

    /** total jvm uptime on all the available processors */
    //long totalElapsedJvmUptime = elapsedJvmUptime * osMXBean.getAvailableProcessors() ;
    long totalElapsedJvmUptime = elapsedJvmUptime;
    //System.out.println("echo cpu processors num " + osMXBean.getAvailableProcessors());

    /** calculate cpu usage as a percentage value
       to convert nanoseconds to milliseconds divide it by 1000000 and to get a percentage multiply it by 100 */
    float cpuUsage = elapsedProcessCpuTime / (totalElapsedJvmUptime * 10000F);



    return (float)(Math.round(cpuUsage*10)/10);
}

答案 3 :(得分:0)

如果您使用的是基于UNIX的操作系统,那就容易多了

final OperatingSystemMXBean mxBean = ManagementFactory.getOperatingSystemMXBean();
if (mxBean instanceof UnixOperatingSystemMXBean) {
  return ((UnixOperatingSystemMXBean) mxBean).getSystemCpuLoad() * 100.0;
}