Java API to get processor load and memory of my Java application

I need an API to get the processor and memory usage of my current process or application in Java.

I have an API to get the getSystemCpuLoad CPU of the whole system, but I need it for a specific process ( getSystemCpuLoad the OperatingSystemMXBean interface)

thanks in advance

+10
source share
3 answers

You can get this data if you use another 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.

+6
source

There is good news and bad news. The bad news is that a software request for CPU usage is not possible using pure Java. There is simply no API for this. A recommended alternative is to use Runtime.exec () to determine the JVM process ID (PID), call an external platform-specific command, such as ps, and analyze its output for the PID of interest. But this approach is fragile at best.

The good news is that a reliable solution can be achieved by going beyond Java and writing a few lines of C code that integrates with a Java application through the Java Native Interface (JNI).

+4
source

Once you get the pid, you can use jstat -gc [insert-pid-here] to find statistics on the behavior of the heap collected by garbage.

jstat -gc Capacity [insert-pid-here] provides information on creating a memory pool and space capabilities.

jstat -gc util [insert-pid-here] will present each generation load as a percentage of its capacity. Useful to get an overview of usage.

0
source

All Articles