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