0

I want to get the following data using java 1.8.

  1. CPU Usage.
  2. Total Physical Memory
  3. Available Memory
  4. Free Memory

I have used OperatingSystemMXBean but it doesn't have methods to get above data.

Also I used Runtime.getRuntime() to get memory size but it return the long value which I unable to convert into MB or GB.

Randy
  • 9,419
  • 5
  • 39
  • 56
Harsh
  • 65
  • 1
  • 9
  • 1
    you can use `OperatingSystemMXBean` https://docs.oracle.com/javase/7/docs/jre/api/management/extension/com/sun/management/OperatingSystemMXBean.html – DimaSan Aug 16 '16 at 12:23
  • 2
    Possible duplicate of [How to monitor the computer's cpu, memory, and disk usage in Java?](http://stackoverflow.com/questions/47177/how-to-monitor-the-computers-cpu-memory-and-disk-usage-in-java) – Rudziankoŭ Aug 16 '16 at 12:24
  • If all else fails, you can investigate Windows API and use [JNA](https://en.wikipedia.org/wiki/Java_Native_Access). –  Aug 16 '16 at 12:25
  • Related: http://stackoverflow.com/questions/2062440/java-cpu-usage-monitoring/14712892#14712892 OperatingSystemMXBean can give wrong results or 'not supported' values, and take a look at the source of javasysmon. – Mark Jeronimus Aug 16 '16 at 12:46
  • If at all possible, I would recommend trying out the SIGAR API: http://stackoverflow.com/questions/47177/how-to-monitor-the-computers-cpu-memory-and-disk-usage-in-java – eighthrazz Aug 16 '16 at 16:41

1 Answers1

0

I have checked the javadocs and seems like they are here: http://docs.oracle.com/javase/7/docs/jre/api/management/extension/com/sun/management/OperatingSystemMXBean.html

However; you should be careful with the imported class. You should use the one from the com.sun.management package, not the one from the java.lang.management package.

bigahega
  • 405
  • 2
  • 6
  • The link shown display the methods of OperatingSystemMXBe‌​an which is avaliable till java 1.7. Currenty I am using Java 1.8 and it has none of the methods which can dispay the result what I mentioned above. – Harsh Aug 16 '16 at 12:46
  • As you can see here: http://docs.oracle.com/javase/8/docs/jre/api/management/extension/com/sun/management/OperatingSystemMXBean.html they are still included in 1.8 – bigahega Aug 16 '16 at 12:47
  • Thanks. I have changed the package to com.sun.management and got all required methods. `But the getProcessCpuLoad()` and `getSystemCpuLoad()` return -1. How to make this work correctly? – Harsh Aug 16 '16 at 13:11
  • As far as I have checked the internals of those methods are *as expected* native. So I would go with my own JNI code. http://www.javaworld.com/article/2077361/learn-java/profiling-cpu-usage-from-within-a-java-application.html might be a good starting point. – bigahega Aug 16 '16 at 13:27
  • Thanks for this useful info. Mentioned code snippet seems a bit complex but I will definitely try to integrate this JNI code. – Harsh Aug 22 '16 at 08:17