Reputation: 604
Is there any way I could find out available or free ram in machine using Java ?
Need this detail so that I could launch my JVM accordingly.
Upvotes: 0
Views: 218
Reputation: 298529
There is an API allowing to get the numbers, but it’s not part of the official API in Java 8 and depends on an optional module, jdk.management
, in JDK 11.
You can use dynamic access to avoid direct code dependencies to unofficial APIs. In the common implementations, i.e. OpenJDK and Oracle’s JDK distribution, it will be available:
import java.lang.management.ManagementFactory;
import javax.management.*;
public class Memory {
public static void main(String[] args) throws JMException {
MBeanServer mBeanServer = ManagementFactory.getPlatformMBeanServer();
ObjectName objectName = new ObjectName("java.lang:type=OperatingSystem");
Long free = (Long)mBeanServer.getAttribute(objectName, "FreePhysicalMemorySize");
Long total= (Long)mBeanServer.getAttribute(objectName, "TotalPhysicalMemorySize");
final double gb = 0x1p-30;
System.out.printf("%.2f GB of %.2f GB free%n", free * gb, total * gb);
total = (Long)mBeanServer.getAttribute(objectName, "TotalSwapSpaceSize");
free = (Long)mBeanServer.getAttribute(objectName, "FreeSwapSpaceSize");
System.out.printf("%.2f GB of %.2f GB swap free%n", free * gb, total * gb);
}
}
Upvotes: 2