简体   繁体   中英

How to get the free memory size (ram) of a virtual machine using JAVA

I'm trying to get the used percentage ram used on a virtual machine.

In local on my computer I achieve it by using :

Double FreeRamSize = (double) mxBean.getFreePhysicalMemorySize() Double TotalRamSize = (double) mxBean.getTotalPhysicalMemorySize()

And it works perfectly fine. But if I deploy my app on a virtual machine, I will only have the total physical memory size and my FreeRamSize will always return 0. I didn't find any tips on internet.

Thank in advance for your help.

You should not need to modify the memory information code to run a virtual machine since the underlying differences between a virtual machine and physical machines RAM should be completely irrelevant to a Java process.

Just for kicks I ran this on my own virtual machine with no problems.

double GiB = Math.pow(2, 30);
OperatingSystemMXBean osBean = ManagementFactory.getPlatformMXBean(OperatingSystemMXBean.class);

Double freeRamSize = (double) osBean.getFreePhysicalMemorySize();
Double totalRamSize = (double) osBean.getTotalPhysicalMemorySize();

System.out.println(freeRamSize / GiB + " / " + totalRamSize / GiB);

1.8224868774414062 / 3.9995040893554688

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM