JVM Memory

Every JVM instance is a process running under the operating system. As every process will have allocated memory, JVM will also have default memory allocated for the process that it is running in. The default JVM's max memory allocation is 64MB. If a program that runs out of 64MB memory during it's execution, JVM will raise an OutOfMemoryError and will be aborted.

If you're sure that your program might need more memory, then you can JVM command line options -Xmx and -Xmn to increase the default memory allocation.

There are few methods like totalMemory(), freeMemory(), gc() etc. defined under java.lang.Runtime class to access or monitor the memory resources.

  • totalMemory() - gives total memory that is allocated for JVM
  • freeMemory() - gives total available memory
  • gc() - garbage collection routine will be executed. Please note that it is not recommended to invoke gc() method as JVM automatically invokes this

Note: java.lang.Runtime object can be created using the factory method Runtime.getRuntime()

MemoryDemo.java

/**
* Demonstration of totalMemory(), freeMemory() and gc().
* @author Santhosh Reddy Mandadi
* @since 09-Sep-2012
* @version 1.0
*/
public class MemoryDemo
{
public static void main(String args[])
{
Runtime runtime = Runtime.getRuntime();
long mem1, mem2;
Integer someints[] = new Integer[1000];
System.out.println("Total memory is: " +runtime.totalMemory());
mem1 = runtime.freeMemory();
System.out.println("Initial free memory: " + mem1);
runtime.gc();
mem1 = runtime.freeMemory();
System.out.println("Free memory after garbage collection: "+ mem1);
for(int i=0; i<1000; i++)
{
someints[i] = new Integer(i); // allocate integers
}
mem2 = runtime.freeMemory();
System.out.println("Free memory after allocation: "+ mem2);
System.out.println("Memory used by allocation: "+ (mem1-mem2));
// discard Integers
for(int i=0; i<1000; i++)
{
someints[i] = null;
}
runtime.gc(); // request garbage collection
mem2 = runtime.freeMemory();
System.out.println("Free memory after collecting" +" discarded Integers: " + mem2);
}
}
Output

>java MemoryDemo
Total memory is: 16252928
Initial free memory: 16047416
Free memory after garbage collection: 16192808
Free memory after allocation: 16009136
Memory used by allocation: 183672
Free memory after collecting discarded Integers: 16192672

>java -Xmn128m MemoryDemo
Total memory is: 125042688
Initial free memory: 122893080
Free memory after garbage collection: 124917032
Free memory after allocation: 120617696
Memory used by allocation: 4299336
Free memory after collecting discarded Integers: 124916896