Showing posts with label Maximum Heap Size. Show all posts
Showing posts with label Maximum Heap Size. Show all posts

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

Heap Memory

Heap is a portion of memory where dynamic allocation and de allocations happen

Heap memory is slightly slower to read from and written to, because pointer access is needed to access heap memory

The JVM allocates Java heap memory from the OS and then manages the heap for the Java application.

Heap doesn't have any restrictions on memory size, it totally depends on Hardware.

Possibility of memory leak, if the heap is not organized properly

What are the initial heap size for an Application
Ideally it is platform and JVM dependent.

Initial Heap values for IBM Java
Platform

Initial size
Maximum Size
AIX®
4 MB
64 MB
IBM® i
4 MB
2 GB
Linux®
4 MB
Half the real memory with a minimum of 16 MB and a maximum of 512 MB
Windows®

4 MB
Half the real memory with a minimum of 16 MB and a maximum of 2 GB
z/OS®
1 MB
64 MB

Initial heap size for Oracle Java
On Server class machines
    initial heap size:
    Larger of 1/64th of the machine's physical memory on the machine or some reasonable minimum. Before J2SE 5.0, the default initial heap size was a reasonable minimum, which varies by platform. You can override this default using the -Xms command-line option.

maximum heap size:
    Smaller of 1/4th of the physical memory or 1GB. Before J2SE 5.0, the default maximum heap size was 64MB. You can override this default using the -Xmx command-line option.

Usefule Links




Increase stack size                                                 Increase Heap Size                                                 Home