Java Program to Set Minimum and Maximum Heap Size
The Heap area is one of the various memory areas present inside the JVM. For every JVM one heap area is available. The Heap area will be created at the time of the JVM startup. Objects and the corresponding instance variable will be stored in the heap area. Every array in java is the object only, hence the array also will be stored in the heap area. The Heap area can be accessed by multi threads hence the data store in heap memory is not threaded safe. The Heap area need not be continuous.
Program to display heap memory statistics:
A java application can communicate with VM by using a runtime object. Runtime class present in java.lang package and it is a singleton class. We can create a runtime object as follows:
Runtime r= Runtime.getRuntime();
Once we get the runtime object we can call the following methods on that object :
- maxMemory() : It returns the number of bytes of max memory allocated to the heap.
- totalMemory() : It returns the number of bytes of the total memory allocated to the heap.
- freeMemory() : It returns the number of bytes of free memory present in the heap
Max memory 134217728 Initial memory 134217728 Free memory 132286176 Consume memory 1931552
Heap memory is finite memory but based on our requirements we can set maximum and minimum heap size i.e we can increase or decrease the heap size based on our requirements. We can do this by using the following java commands at runtime.
1. -Xmx to set maximum heap size (max memory)
java -Xmx512m heapMemory
This command sets the maximum heap size as 512Mb.
Max memory 134.217728 Initial memory 134.217728 Free memory 132.285184 Consume memory 1.932544
2. -Xms: we can use this command to set a minimum or initial heap size.
java -Xms64m heapMemory
This command set the minimum size as 64Mb i.e totalMemory().
Max memory 134.217728 Initial memory 134.217728 Free memory 132.285192 Consume memory 1.932536
Please Login to comment...