tags:

views:

1678

answers:

5
+9  Q: 

CPU load from Java

Is there a way to get the current cpu load under Java without using the JNI?

+1  A: 

Under Linux you could use Runtime.exec() to execute “uptime” and evaluate the output. I don’t there’s a better way under Linux, and I don’t think there’s an equally “convenient” way under Windows.

Bombe
+2  A: 

On linux you could just read the file /proc/loadavg, where the first three values represent the load averages. For Windows you probably have to stick to JNI.

welterde
+14  A: 

Use the ManagementFactory to get an OperatingSystemMXBean and call getSystemLoadAverage() on it.

Joachim Sauer
Weird. The getSystemLoadAverage link doesn't go to the anchor, but when I went in to edit it, it did work. Maybe the system now auto-replaces () with %28%29, even in anchors.
Michael Myers
Well, when I edited it, I got it wrong the first time. Maybe we had a human race condition. Having the link seemed to make the answer even more perfect, though.
Bob Cross
What I meant was that the link still shows as #getSystemLoadAverage%28%29. The Runtime.exec() link in Bombe's answer below has the same issue, and editing it shows exec(java.lang.String) instead of exec%28java.lang.String%29. Do either of those work for anyone else?
Michael Myers
I don't think I see what you see: I'm running Firefox on Fedora 9 and I see this for the getSystemLoadAverage() link: http://java.sun.com/javase/6/docs/api/java/lang/management/OperatingSystemMXBean.html#getSystemLoadAverage()
Bob Cross
Must be an IE7 thing then. (I wish I could use Firefox here.)
Michael Myers
I am pretty sure this doesn't work on Windows XP.
Peter Lawrey
+2  A: 

This does involve JNI but there is a GPL library from Hyperic called Sigar that provides this information for all the major platforms, as well as a bunch of other OS-dependent stats like disk usage. It's worked great for us.

Alex Miller
A: 

If you're using the JRockit JVM you could use JMAPI. It works for JDK 1.4, 1.5 and 1.6.

System.out.println("Total CPU-usage:" + JVMFactory.getJVM().getMachine().getCPULoad());

System.out.println("Total JVM-load :" + JVMFactory.getJVM().getJVMLoad());

for(Iterator it = JVMFactory.getJVM().getMachine().getCPUs().iterator(); it.hasNext();)
{
   CPU cpu = (CPU)it.next();
   System.out.println("CPU Description: " + cpu.getDescription());
   System.out.println("CPU Clock Frequency: " + cpu.getClockFrequency());
   System.out.println("CPU Load: " + cpu.getLoad());
   System.out.println();
}
Kire Haglin