Java API to get CPU and memory usage of my java application
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());
}}
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).
Related videos on Youtube
chang zang
Updated on September 15, 2022Comments
-
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
ofOperatingSystemMXBean
interface)Thanks in advance
-
Vishy about 8 yearsIt 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 about 8 yearsGives Compilation error : The method getProcessCpuLoad() is undefined for the type OperatingSystemMXBean.
-
RubioRic about 8 years@PSM Check the import. Are you sure that you are importing com.sun.management.OperatingSystemMXBean?
-
RubioRic about 8 years@PSM I think that you are still using java.lang.management.OperatingSystemMXBean
-
Cardinal System over 4 yearsIs there a Java 8 solution? The above gives me the error
The method getProcessCpuLoad() is undefined for the type OperatingSystemMXBean
. -
RubioRic over 4 years@CardinalSystem Have you checked the imported package? I've used it with Java 8