Java API to get CPU and memory usage of my java application

11,886

Solution 1

You can obtain that data if you use a different OperatingSystemMXBean.

Check the imported package: com.sun.management.OperatingSystemMXBean.

 import java.lang.management.ManagementFactory;
 import com.sun.management.OperatingSystemMXBean;

 public class Test {

 public static void main(String[] args) {
       OperatingSystemMXBean operatingSystemMXBean = 
          (OperatingSystemMXBean) ManagementFactory.getOperatingSystemMXBean();
       System.out.println(operatingSystemMXBean.getProcessCpuLoad());
 }}

https://docs.oracle.com/javase/7/docs/jre/api/management/extension/com/sun/management/OperatingSystemMXBean.html

If I'm not mistaken, this class is included in rt.jar, present in your java runtime.

Solution 2

There is the good news and the bad news. The bad news is that programmatically querying for CPU usage is impossible using pure Java. There is simply no API for this. A suggested alternative might use Runtime.exec() to determine the JVM's process ID (PID), call an external, platform-specific command like ps, and parse its output for the PID of interest. But, this approach is fragile at best.

The good news, however, is that a reliable solution can be accomplished by stepping outside Java and writing a few C code lines that integrate with the Java application via Java Native Interface (JNI).

Share:
11,886

Related videos on Youtube

chang zang
Author by

chang zang

Updated on September 15, 2022

Comments

  • chang zang
    chang zang over 1 year

    I need an API to get CPU & memory usage of my current process or application in java.

    I've got an API to get the CPU usage of the complete system but I need it for a particular process (getSystemCpuLoad of OperatingSystemMXBean interface)

    Thanks in advance

    • Vishy
      Vishy about 8 years
      It depends on what you mean by memory usage; do you mean resident memory, virtual memory, heap in use, live objects, These can be very different.
  • P S M
    P S M about 8 years
    Gives Compilation error : The method getProcessCpuLoad() is undefined for the type OperatingSystemMXBean.
  • RubioRic
    RubioRic about 8 years
    @PSM Check the import. Are you sure that you are importing com.sun.management.OperatingSystemMXBean?
  • RubioRic
    RubioRic about 8 years
    @PSM I think that you are still using java.lang.management.OperatingSystemMXBean
  • Cardinal System
    Cardinal System over 4 years
    Is there a Java 8 solution? The above gives me the error The method getProcessCpuLoad() is undefined for the type OperatingSystemMXBean.
  • RubioRic
    RubioRic over 4 years
    @CardinalSystem Have you checked the imported package? I've used it with Java 8