By augusto
via sellmic.com
Published: Jul 23 2011 / 11:06
First in a series of "hidden Java 7 features", highlighting lesser known new features in the latest Java release. This one gives an overview of the new capabilities to monitor process and system CPU loads, with a CPU monitor GUI example.



Comments
augusto replied ago:
Fixed the JNLP link to the demo CPU monitor GUI app, if you tried it before and it failed (still needs Java 7), please give it another try. Sorry about that!
javakata replied ago:
OperatingSystemMXBean.getSystemLoadAverage() indeed doesn't work with Java 6 on Windows 7 (haven't tried the other versions of Windows, but since they're already or about to be discountinued, it doesn't really matter). If you REALLY need to get the cpu load on windows 7 in a way that'll work on Java 6 as well, just use getProcessCPUTime() from the OperatingSystemMXBean. Measure it twice for a certain interval, also measure the nanoseconds that have passed between those calls (System.currentTimeNano()), and then divide the cpuTime (difference between the last and the first values returned by getProcessCPUTime()) by the time passed (difference between the two values returned by the last and the first calls to System.currentTimeNano()). Multiply this value by 100 if you want to get someting like 72 (as in 72% cpu load). And as a small gotcha, if you try this on a computer that was bought sometimes after 2005, and you get values such as 182% (!!) just divide that value AGAIN by the number of cpu cores currently found on the machine (which you can get by calling Runtime.getRuntime().availableProcessors()) to get the average percent load on ALL cpu cores.
augusto replied ago:
Wow, that's a great tip! Makes me glad they added this of course :-)
Voters For This Link (19)
Voters Against This Link (0)