Getting OS memory size from java

前端 未结 3 752
醉梦人生
醉梦人生 2020-12-20 14:02

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

Runtime.getRuntime().maxMemory()

returns the

相关标签:
3条回答
  • 2020-12-20 14:26

    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.

    0 讨论(0)
  • 2020-12-20 14:33

    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"

    0 讨论(0)
  • 2020-12-20 14:35
    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.

    0 讨论(0)
提交回复
热议问题