Each time object is created in Java it goes into the area of memory known as heap. In a multithreaded application each thread will have its own stack but will share the same heap. This is  why care should be taken in our code to avoid any  concurrent access issues in the heap space.

 

The heap may be of a fixed size or may be expanded. The heap is created on virtual machine start-up. If we have complicated programs or  big caching which might create lot of objects in memory so we may need bigger heap size. In this case it is possible that JVM  will throw java.lang.OutOfMemoryError instances when attempting to instantiate objects.

 

 We can increase heap size using the following command

 

java -Xms64m -Xmx256m MyProgram

 

Here we are setting minimum heap to 64MB and maximum heap to 256MB for a Java program MyProgram.

 

Following are the options available for changing the Java heap size

-Xms<size>        set initial Java heap size

-Xmx<size>        set maximum Java heap size

-Xss<size>        set java thread stack size

 

Reading Default Heap size

We can get to know how large the object heap is and  how much of it is left, using the methods provided by Runtime class. Runtime  class encapsulates the running Java interpreter process. We can use totalMemory and freeMemory methods in Runtime to get the information.

 

public class MyprogramHeapSize {

            public static void main(String[]args){

                        //Get the jvm heap size.

                        long heapSize = Runtime.getRuntime().totalMemory();

                        //Print the jvm heap size.

                        System.out.println("Heap Size = "+heapSize);

            }

 

}

 

 

Output of this program is

Heap Size = 55312384




Sandeep Joshi
Mathematics, Technology and Programming are my passion. I am a part of Java Ecosystem and through this blog, I contribute to it. I am here to blog about my interests, views and experiences.
I am on Google+ and Facebook.
I feel proud to be listed as a "National Memory Record Holder" in the Limca Book of Records, 2009 and have attempted for an International Memory record in the Guiness Book of Records. I can remember the value of PI upto 10,000 digits after the decimal (3.1415.....). You can contact me on javagenious.com(At)gmal.com ; I would like to hear from you :)