Getting JVM heap size, used memory, total memory using Java Runtime

java-textReading runtime information about Java is useful sometime when your application is struggling in getting resources. System Memory is one of the main resource that an application developer has to consider while managing the application.

Hence sometimes it is beneficial to see what amount of memory is your application using and what is the free memory in system.

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.

/**
* Class: TestMemory
* @author: Viral Patel
* @description: Prints JVM memory utilization statistics
*/
public class TestMemory {

	public static void main(String [] args) {

		int mb = 1024*1024;

		//Getting the runtime reference from system
		Runtime runtime = Runtime.getRuntime();

		System.out.println("##### Heap utilization statistics [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);
	}
}

You may also want to print the memory utilization in Kilobytes KBs. For that just assign 1024 value to the int variable mb.



2 Comments

  • scottyab wrote on 8 October, 2009, 16:49

    Thanks for this, saved me typing ;)

  • Vish wrote on 13 November, 2009, 19:52

    Hi Viral,
    I want to get JVM heap size of WebS portal server pre/post its restarts.

    Is there any way I can run the above script on RHEL linu box and get it working.

    Please advise.

    Vishwanath

Leave a Reply

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

*

Copyright © 2012 ViralPatel.net. All rights reserved.