Diagnostics.java 文件源码

java
阅读 29 收藏 0 点赞 0 评论 0

项目:momo-2 作者:
private static double getCpuLoad() {
    // http://stackoverflow.com/questions/18489273/how-to-get-percentage-of-cpu-usage-of-os-from-java
    try {
        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();

        // usually takes a couple of seconds before we get real values
        if (value == -1.0)    
            return Double.NaN;
        // returns a percentage value with 1 decimal point precision
        return ((int)(value * 1000) / 10.0);
    } catch(Exception e) {
        return Double.NaN;
    }
}
评论列表
文章目录


问题


面经


文章

微信
公众号

扫码关注公众号