I have been trying to write a simple CPU utilization monitor as a proof of concept for a larger project. I am writing in Eclipse Juno. When I press "Run", my application works as expected- the CPU utilization is displayed as a percent that updates once every second. However, when I export it to an executable jar, the application seems to lock up- it never displays the percentage, and it never updates. I have determined that the GUI is fine, but for some inexplicable reason, my cpuUtilization method never returns a percentage without ever throwing an exception. Even odder, this problem only happens when the program is exported. SIGAR's documentation is pretty atrocious, but I think I am using it correctly. All the rest of the program seems to work, so I'll only include the CPUReader class. It is constructed when the CPUMonitorGUI class is constructed, and cpuUtilization is called once per second by CPUMonitorGUI. Some additional notes: I have imported sigar.jar but not log4j.jar. Doing so makes no difference. Also, in Eclipse, I have selected "Package Required Libraries into generated JAR" when I export.
package cpuperc;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.Humidor;
import org.hyperic.sigar.SigarProxy;
public class CPUReader
{
static Humidor h;
public CPUReader()
{
h = Humidor.getInstance();
}
public double cpuUtilization() throws SigarException
{
//Returns CPU utilization as truncated two-decimal percent
SigarProxy sp = h.getSigar();
CpuPerc cp = sp.getCpuPerc();
double combined;
double total;
double idle;
double percentUsed;
int truncate = 0;
//get CPU times
combined = cp.getCombined();
idle = cp.getIdle();
total = idle + combined;
//determine percent and truncate
percentUsed = ((double)combined/total)*100;
truncate = (int)(percentUsed*100.0);
percentUsed = (double)truncate/100;
return(percentUsed);
}
}
Thanks!
After some more experimentation, I found out that the program was freezing up because it was looking for the SIGAR libraries specific to the operating system and architecture. In this case, it wanted the 64-bit Universal Mac OS X drivers. However, SIGAR provided these as .dylib files, which Eclipse refused to load. The .dylib files had to be packaged in a .zip archive, which was then added to the Eclipse build path.