Thursday 13 February 2014

How to increase Heap size in java

Run the following program
 
class HeapEx{
 public static void main(String args[]){
  HeapEx obj[] = new HeapEx[100000000];
  
  for(int i=0; i<100000000; i++)
   obj[i] = new HeapEx();
   
  System.out.println("I am done");
 }
}
Exception in thread "main" java.lang.OutOfMemoryError: Java heap space
at HeapEx.main(HeapEx.java:8)

OutOfMemoryError thrown when the Java Virtual Machine unable to allocate memory for an object, and no more memory could be made available by the garbage collector.

To Increase the heap size, java provides an option -Xmx
Option
Description
-Xms
Set initial and minimum heap size
-Xmx
Set maximum heap size

The JVM heap can vary its Current heap size between two preconfigured memory boundaries – the initial heap size (defined by the –Xms option) and the maximum heap size (defined by the –Xmx option)

Syntax
-Xms<size>[g|G|m|M|k|K]
-Xmx<size>[g|G|m|M|k|K]

To make the above program run, I increased the size of heap memory to 5000mb like below

java -Xmx5000M HeapEx

Output
I am done

Heap memory                                                 Object Creation and destruction                                                 Home

No comments:

Post a Comment