jconsole 上进程的概览选项卡向我显示了 CPU 使用率百分比。有没有给我这个值的 MBean?它的 ObjectName 是什么?
最佳答案
更新:在 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 之间的 double 形式返回,因此只需乘以 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 或 future 更新中不可用的风险,因此您应该决定是否愿意承担这种风险。见 https://www.java.net/community-item/hidden-java-7-features-%E2%80%93-system-and-process-cpu-load-monitoring更多。
关于jvm - Sun JVM 上的 CPU 使用率 (%) MBean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3044841/