Using the Java Runtime API for JVM Memory Details
Java’s Runtime class provides 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.
The following is a 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.
From http://viralpatel.net/blogs
- Login or register to post comments
- 6014 reads
- Printer-friendly version
(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)










Comments
mwildam replied on Wed, 2009/05/20 - 11:27am
Thanks for the article!
I found out that the VM just gives me 5 MB of total memory. It would be now interesting in which vm options one has to modify to change the results returned by the functions above (see also Java Hotspot VM options).
Russ replied on Thu, 2009/05/21 - 12:20am
Good tip and you can get more detailed information from java.lang.management.
and you can get some OS level memory information from com.sun.management.OperatingSystemMXBean if java.lang.management.OperationSystemMXBean implements that interface.
green123xyz replied on Fri, 2009/07/17 - 12:10am