Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

java
communitycreator
jvm

How to get the free memory in JVM using Java

abhilash

What is the Runtime class in Java?

The Runtime class has methods that interface and interact with the environment in which the application is run.

The freeMemory() method

The freeMemory() method of the Runtime class is used to retrieve the free memory currently available to the Java Virtual Machine (JVM) for future objects. The value returned by this method is in bytes.

Method signature

public native long freeMemory()

Return value

This method returns the free memory available to JVM.

Example

public class Main {

    public static void main(String[] args){
        Runtime currentRuntime = Runtime.getRuntime();
        System.out.println("Runtime.freeMemory() = " + currentRuntime.freeMemory() + " bytes");
    }
}
Use of freeMemory() method

Explanation

  • Line 4: The current runtime of the application is retrieved using the getRuntime() method of the Runtime class.
  • Line 5: The free memory available to the JVM is obtained by invoking freeMemory() method on the current runtime retrieved in line 4.

RELATED TAGS

java
communitycreator
jvm
RELATED COURSES

View all Courses

Keep Exploring