Skip to content

Instantly share code, notes, and snippets.

@mrWinston
Last active February 2, 2016 11:57
Show Gist options
  • Select an option

  • Save mrWinston/5e84d3994fa8ce0fd915 to your computer and use it in GitHub Desktop.

Select an option

Save mrWinston/5e84d3994fa8ce0fd915 to your computer and use it in GitHub Desktop.
Get the CPU-usage of the process calling the method #java #Mbeans #cpu #utiilities
/* This program is free software. It comes without any warranty, to
* the extent permitted by applicable law. You can redistribute it
* and/or modify it under the terms of the Do What The Fuck You Want
* To Public License, Version 2, as published by Sam Hocevar. See
* http://www.wtfpl.net/ for more details.
*/
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 0.0;
}
Attribute att = (Attribute) list.get(0);
Double value = (Double) att.getValue();
if (value < 0.0) {
return 0.0; // usually takes a couple of seconds before we get real values
}
return ((int) (value * 1000) / 10.0); // returns a percentage value with 1 decimal point precision
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment