Skip to main content

Getting CPU Usage into my java program.

1 reply [Last post]
itamar123
Offline
Joined: 2009-04-20

Hello,

I am looking for a way to get and display the CPU usage in my JAVA program.
- is there any may doing it programmly?
- or is there any external tool (in the JDK) which i can use to get the cpu usage
if there is how am i communicate with the tool?

Reply viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.
msemtd
Offline
Joined: 2008-05-16

You can use the OperatingSystemMXBean to get various statistics. The following is part of a class that tracks CPU usage of the running VM process..

// Find a management bean to get CPU load...
java.lang.management.OperatingSystemMXBean o = ManagementFactory
.getOperatingSystemMXBean();
if (o instanceof com.sun.management.OperatingSystemMXBean) {
osMxBean = (com.sun.management.OperatingSystemMXBean) o;
nProcessors = osMxBean.getAvailableProcessors();
}
rtMxBean = ManagementFactory.getRuntimeMXBean();

...then routinely...

// Get uptime of the VM in milliseconds...
long uptime = rtMxBean == null ? 1 : rtMxBean.getUptime();
// Get the CPU time of the process in nanoseconds...
long processCpuTime = osMxBean == null ? 0 : osMxBean
.getProcessCpuTime();
// Call delegate to calculate...
update(uptime, processCpuTime);

...then my update method calculates and updates a property cpuUsage (with PropertyChangeSupport)...

// Avoid meaningless calculations if first time round or if time has
// not moved forwards(!)...
if (lastUptime > 0L && uptime > lastUptime) {
long elapsedCpu = processCpuTime - lastProcessCpuTime;
long elapsedTime = uptime - lastUptime;
// Avoid erroneous calculation of over 100% as a possible result of
// values being retrieved independently
cpuUsage = Math.min(100F, elapsedCpu
/ (elapsedTime * 10000F * nProcessors));
}
lastUptime = uptime;
lastProcessCpuTime = processCpuTime;

... Hope that helps.