How to get Free, Used and Total Memory in Java ?

As you know that Java does the automatic garbage collection which you need not worry about. However sometime you want to know how large the java heap space is and how much of it is left. Information about Free, Used and Total memory in java can be used for checking your code efficiency.

To obtain these values, use the java.lang.Runtime.totalMemory( ) and java.lang.Runtime.freeMemory( ) methods.

The java.lang.Runtime.totalMemory() method returns the total amount of memory in the Java virtual machine. The value returned by this method may vary over time, depending on the host environment. Note that the amount of memory required to hold an object of any given type may be implementation-dependent.

Below code shows how to get Free, Used and Total Memory in Java –

 * Created on Apr 7, 2015 Copyright(c) All Rights Reserved.

 * This java program shows you how to get Free, Used and Total Java Memory
 * @author
public class MemoryStats {
    public static void main(String[] args){
        int mb = 1024 * 1024; 
		// get Runtime instance
		Runtime instance = Runtime.getRuntime();
		System.out.println("***** Heap utilization statistics [MB] *****\n");
		// available memory
		System.out.println("Total Memory: " + instance.totalMemory() / mb);
		// free memory
		System.out.println("Free Memory: " + instance.freeMemory() / mb);
		// used memory
		System.out.println("Used Memory: "	+ (instance.totalMemory() - instance.freeMemory()) / mb);
		// Maximum available memory
		System.out.println("Max Memory: " + instance.maxMemory() / mb);

Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.