Last active
February 2, 2016 11:57
-
-
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 file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* 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