title: Using OperatingSystemMXBean to get CPU usage
body: <p>I'm trying to use Java to get the percentage of CPU used by the currently running Java Virtual Machine. My research has pointed me to using the <code>com.sun.management.OperatingSystemMXBean</code> class. Following examples online, I've written the following:</p>
  
  <pre><code>import java.lang.management.ManagementFactory;
  import com.sun.management.OperatingSystemMXBean;
  
  
  public class TestClass {
  
  public static void main (String[] args) {
      OperatingSystemMXBean bean = (com.sun.management.OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
  
      System.out.println(bean.getProcessCpuLoad());
      System.out.println(bean.getSystemCpuLoad());
  
      }
  
  }
  </code></pre>
  
  <p>After testing this on two machines, I can't stop getting a result of <code>-1.0</code> for both calls. I have tried running this code using both 64- and 32-bit versions of Java 7 and 6 through various methods. Still, all I get is a print out of <code>-1.0</code> which, <a href="http://docs.oracle.com/javase/7/docs/jre/api/management/extension/com/sun/management/OperatingSystemMXBean.html" rel="noreferrer">according to the Javadocs</a>, </p>
  
  <p><code>All values betweens 0.0 and 1.0 are possible depending of the activities going on in the system. If the system recent cpu usage is not available, the method returns a negative value.</code></p>
  
  <p>I don't know what else to do here. Getting the CPU load is critical, and I'd like to avoid using another library like Sigar. Anybody have any recommendations or have any insights into this problem?</p>