10

Are there any way to get the size of the total memory on the operating system from java? Using

Runtime.getRuntime().maxMemory()

returns the allowed memory for the JVM, not of the operating system. Does anyone have a way to obtain this (from java code)?

soren.enemaerke
  • 4,770
  • 5
  • 53
  • 80

4 Answers4

17
com.sun.management.OperatingSystemMXBean bean =
  (com.sun.management.OperatingSystemMXBean)
    java.lang.management.ManagementFactory.getOperatingSystemMXBean();
long max = bean.getTotalPhysicalMemorySize();

returns available RAM size for JVM (limited by 32bit), not the heap size.

khachik
  • 28,112
  • 9
  • 59
  • 94
  • 1
    "Access restriction: The type 'OperatingSystemMXBean' is not API" in Java 8, referring specifically to the one in `com.sun.management`. – Brian McCutchon Mar 14 '16 at 03:24
3

There is no Java-only way to get that information. You may use Runtime.exec() to start OS-specific commands, e.g. /usr/bin/free on Linux. Still on Linux systems, you can use Java file access classes (FileInputStream) to parse /proc/meminfo.

Thomas Pornin
  • 72,986
  • 14
  • 147
  • 189
3

that is not possible with pure Java, your program runs on java virtual machine, and therefore it is isolated from OS. I suggest 2 solutions for this:

1) You can use a JNI and call a C++ function to do that
2) Another option is to use Runtime.exec(). Then you have to get the info from "cat /proc/meminfo"

Stephan
  • 41,764
  • 65
  • 238
  • 329
Caner
  • 57,267
  • 35
  • 174
  • 180
0

You can get the RAM usage with this. This is the same value that taskmanager in windows shows

    com.sun.management.OperatingSystemMXBean bean = (com.sun.management.OperatingSystemMXBean)java.lang.management.ManagementFactory.getOperatingSystemMXBean();
    double percentage = ((double)bean.getFreeMemorySize() / (double)bean.getTotalPhysicalMemorySize()) * 100;
    percentage = 100 - percentage;
    System.out.println("RAM Usage: " + percentage + "%");
Coderman69
  • 69
  • 7