How to get the total memory in JVM using Java
What is the Runtime class in Java?
The Runtime class has methods that interface and interact with the application’s runtime environment.
The totalMemory() method
The totalMemory() method of the Runtime class is used to retrieve the total memory available in the Java Virtual Machine (JVM). The value returned by this method is in bytes.
Syntax
public native long totalMemory()
Return value
This method returns the total memory available to the JVM.
Example
public class Main {public static void main(String[] args){Runtime currentRuntime = Runtime.getRuntime();System.out.println("Runtime.totalMemory() = " + currentRuntime.totalMemory() + " bytes");}}
Explanation
- Line 4: We retrieve the current runtime of the application using the
getRuntime()method of theRuntimeclass. - Line 5: We obtain the total memory JVM will have by calling the
totalMemory()method on thecurrentRuntimeretrieved in line 4.