Friday, 20 February 2015

Getting JVM heap size, used memory and Total Memory


Runtime class provides useful information related to JVM at runtime. The current runtime can be obtained from the getRuntime method of Runtime class.

Runtime class provides below methods to get memory information.
public long freeMemory()
Returns an approximation to the total amount of memory currently available in JVM.

public long totalMemory()
Returns the total amount of memory in the Java virtual machine.

public long maxMemory()
Returns the maximum amount of memory that the Java virtual machine will attempt to use.

import java.util.*;

public class TestMemory {

    private static final int MB = 1024 * 1024;
    private static Runtime runtime = Runtime.getRuntime();
    private static long totalMemory, freeMemory, maxMemory;

    /* Print memory details */
    public static void getMemoryDetails() {
        totalMemory = runtime.totalMemory();
        freeMemory = runtime.freeMemory();
        maxMemory = runtime.maxMemory();

        System.out.println((totalMemory / MB) + "\t" + (totalMemory - freeMemory) / MB + "\t" + (freeMemory / MB) + "\t" + (maxMemory / MB));
    }

    public static void main(String[] args) {
        List<Integer> myList = new ArrayList<Integer>();

        System.out.println("Total\tUsed\tFree\tMax");
        for (int i = 0; i < 10000000; i++) {
            myList.add(i);
            if (i % 1000000 == 0) {
                getMemoryDetails();
            }
        }
    }
}


Sample Runs
E:\>java TestMemory
Total   Used    Free    Max
15      0       14      247
47      20      26      247
84      48      36      247
84      79      5       247
156     77      78      247
156     116     39      247
156     130     25      247
247     166     81      247
247     181     66      247
247     173     74      247

E:\>java -Xms64m -Xmx1000m TestMemory
Total   Used    Free    Max
61      1       60      966
61      25      36      966
61      52      8       966
108     73      35      966
108     87      21      966
189     116     73      966
189     130     58      966
189     181     7       966
348     157     190     966
348     173     175     966

E:\>java -Xms64m -Xmx1500m TestMemory
Total   Used    Free    Max
61      1       60      1450
61      25      36      1450
61      52      8       1450
108     73      35      1450
108     87      21      1450
189     116     73      1450
189     130     58      1450
189     181     7       1450
348     157     190     1450
348     173     175     1450


No comments:

Post a Comment