Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the physical memory size in Java?

I'm writing an installer that will tune the configuration of the product for the particular hardware on which it will be run. In particular, I want to determine how much physical RAM is installed in the system so I can estimate how much memory to allocate to the product when it runs.

Ideally, I'd like to do this in a platform-independent, pure Java way, as the installer will need to run on several different platforms, but in case this isn't possible, solutions for Windows are preferred as that's the most common deployment platform.

In this case, it's safe to assume that the product will be the only/main application running on the box, so I don't have to worry about squeezing anyone else out. I don't want to over-allocate as this, in our experience, can hurt performance.

like image 220
Martin McNulty Avatar asked Jun 04 '09 13:06

Martin McNulty


People also ask

How do I get system memory in Java?

How to get total Memory in Java. You can use Runtime. getRuntime. totalMemory() to get total memory from JVM which represents the current heap size of JVM which is a combination of used memory currently occupied by objects and free memory available for new objects.

How do you find how much memory is used and total memory in Java?

totalMemory() - Runtime. getRuntime(). freeMemory()) / 1024);

Can you access memory in Java?

Java was initially designed as a safe, managed environment. Nevertheless, Java HotSpot VM contains a “backdoor” that provides a number of low-level operations to manipulate memory and threads directly. This backdoor – sun.


1 Answers

You can use the following Java code to query the physical memory:

com.sun.management.OperatingSystemMXBean os = (com.sun.management.OperatingSystemMXBean)
     java.lang.management.ManagementFactory.getOperatingSystemMXBean();
long physicalMemorySize = os.getTotalPhysicalMemorySize();

But the package com.sun.management is optional and need not be available on every platform.

like image 91
Horcrux7 Avatar answered Sep 30 '22 11:09

Horcrux7