I'm writing a Java application that needs to check the maximum amount of RAM available in the system (not the one available for the VM). Is there a portable way to do so?
Thanks a lot :-)
I'm writing a Java application that needs to check the maximum amount of RAM available in the system (not the one available for the VM). Is there a portable way to do so?
Thanks a lot :-)
Short answer: no, no portable way to get total RAM.
Of course, there is a very easy way to get total JVM memory (java.lang.Runtime.maxMemory()
), but this is not what you're after.
To get total system RAM size, you will need to resort to native system calls (which are totally not portable).
you can use JNI call to query your native OS
but you will have to restart the JVMwith new memory arguments if you want more memory for the JMV
JMX you can access the FreePhysicalMemorySize and TotalPhysicalMemorySize attributes of java.lang:type=OperatingSystem. These attributes are not really documented in the JavaDocs so they are probably not guaranteed on all JVMs and platforms, but they were available to me (using Sun's JVM).
In your Java code you can get access to the MBean via: ManagementFactory.getOperatingSystemMXBean()
These properties are documented in the JavaDoc for Sun's implementation so I think you may rely on them if your application runs on their JVM.
"maximum amount of RAM available" - so not the physical RAM installed I assume? But the part that's (1) accessible to the OS, (2) not in use to store OS code, and (3) not in use to store OS data?
The problem is that this answer changes every millisecond as the OS flushes dirty pages to disk, thus reducing part (3) above. And if RAM is really needed, the OS will often swap parts of itself out, so the amount of RAM allocated for (2) is also fuzzy.
And we'll probably need to skip the case of a virtualized system where the OS itself runs in a VM, so you'd have a JVM in an OS in a VM.