How to get JVM heap size, used memory, total memory using Java Runtime

Java’s Runtime class provide lot of information about the resource details of Java Virtual Machine or JVM. The memory consumed by the JVM can be read by different methods in Runtime class.
Following is the small example of getting/reading JVM Heap Size, Total Memory and used memory using Java Runtime api.

public class Memoryusage{
    public static void main(String [] args) {
        int mb = 1024*1024;
        //Getting the runtime reference from system
        Runtime runtime = Runtime.getRuntime();
        System.out.println("Heap Space usage in MB");
        //Print used memory
        System.out.println("Used Memory:"
            + (runtime.totalMemory() - runtime.freeMemory()) / mb);
        //Print free memory
        System.out.println("Free Memory:"
            + runtime.freeMemory() / mb);
        //Print total available memory
        System.out.println("Total Memory:" + runtime.totalMemory() / mb);
        //Print Maximum available memory
        System.out.println("Max Memory:" + runtime.maxMemory() / mb);

No comments:

Post a Comment

Please Provide your feedback here