jmx - How to get percentage of CPU usage of OS from java -


i want calculate percentage of cpu usage of os java code.

  1. there several ways find unix command [e.g. using mpstat, /proc/stat etc...] , use runtime.getruntime().exec

but don't want use system calls.

i tried managementfactory.getoperatingsystemmxbean()

operatingsystemmxbean osbean =          (operatingsystemmxbean) managementfactory.getoperatingsystemmxbean(); system.out.println(osbean.getsystemloadaverage()); 

but gives cpu load not cpu usage. there anyway find usage percentage?

in java 7 can so:

public static double getprocesscpuload() throws exception {      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();      // takes couple of seconds before real values     if (value == -1.0)      return double.nan;     // returns percentage value 1 decimal point precision     return ((int)(value * 1000) / 10.0); } 

Comments

Popular posts from this blog

Unable to remove the www from url on https using .htaccess -