Although Java provides automatic garbage collection, sometimes you will want to know how large the object heap is and how much of it is left. You can use this information, for example, to check your code for efficiency or to approximate how many more objects of a certain type can be instantiated. To obtain these values, use the totalMemory( ) and 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.
Java Code
package com.crunchify.tutorials; /** * @author Crunchify.com */ public class CrunchifyJVMParameters { 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); } }
Output:
##### Heap utilization statistics [MB] ##### Total Memory: 71 Free Memory: 70 Used Memory: 0 Max Memory: 1061