Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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

like image 922
chang zang Avatar asked Apr 15 '16 12:04

chang zang


2 Answers

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.

like image 134
RubioRic Avatar answered Sep 23 '22 01:09

RubioRic


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).

like image 31
P S M Avatar answered Sep 24 '22 01:09

P S M