4

I have a piece of code that caclulates the total RAM in my system [not Java VM Heap Size].

It is as follows:

        OperatingSystemMXBean operatingSystemMXBean = 
            ManagementFactory.getOperatingSystemMXBean();

        Method m = operatingSystemMXBean.getClass().
                    getDeclaredMethod("getTotalPhysicalMemorySize");

        m.setAccessible(true);

        Object value = m.invoke(operatingSystemMXBean);

        if (value != null)
        {
            System.out.println(value);
        }

The problem with the above piece of code is that it gives me incorrect values sometimes. For example in a system with 8 GB of RAM, using a 32 bit JVM, it shows 4 GB. I guess it is because the JVM is 32 bit and using 32 bits 4 GB is the maximum that it can address.

Can anyone suggest ways/workarounds for this. Basically how do we get the total RAM in a system using a 32 bit JVM.

Full details of my System are as follows:

OS : Windows 7
CPU : Intel i7
JDK : Sun Java 1.6 Update 21, 32 bit
RAM : 8 GB

Swaranga Sarma
  • 13,055
  • 19
  • 60
  • 93
  • Not sure if this helps, but it has some info: http://stackoverflow.com/questions/25552/using-java-to-get-os-level-system-information – bezmax Jul 14 '11 at 08:50
  • Here is exactly the same question with some answers: http://stackoverflow.com/questions/4335356/getting-os-memory-size-from-java – Stas Jul 14 '11 at 09:04

1 Answers1

2

Cannot think of a pure Java way, but you can use Runtime.exec() to run the following command

wmic MEMPHYSICAL Get MaxCapacity

EDIT: Correction - the above gives the maximum capacity for installing RAM. Try the OS alias like below:

wmic OS Get TotalVisibleMemorySize
kjp
  • 3,086
  • 22
  • 30