tags:

views:

170

answers:

4

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 :-)

+3  A: 

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).

Yuval A
I feared so. Thanks nevertheless :-)I guess I will have to write a top | grep for linux, and come up with some fancy solution for Windows.
Thrawn
+1  A: 

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

Alon
+4  A: 

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.

Fried Hoeben
This might work sporadically. I wouldn't count on it given different JVMs and OSs.
Yuval A
Tested it. It works on Unix and MacOS.It's not really 100% portable, as you have to cast the MXbean object to a system specific MX Bean, but nevertheless, quite a nice solution.
Thrawn
A: 

"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.

MSalters