
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Change/Increase Heap Size of the Java Virtual Machine
A Java program can execute in the Java Virtual Machine (JVM) and uses the heap memory to manage the data. If our Java program requires more memory, there is a possibility that the Java Virtual Machine(JVM) will begin to throw OutOfMemoryError instances when attempting to instantiate an object in Java.
How to change/increase the JVM Heap Size?
In Java, it is possible to increase the heap size allocated by the JVM:
- -Xms:
- Set an initial Java heap size
- JVM automatically manages the heap memory but we can tell it how much memory to start with using -Xms
Syntax
java -Xms<size> ClassName
- -Xmx:
- Set the maximum Java heap size.
- When the program uses more memory than the JVM memory also increases, but we can put a limit by using -Xmx.
Syntax:
java -Xmx<size> ClassName
- -Xss
- Set the Java thread stack size
Syntax:
java -Xss<size> ClassName
Methods to Change Heap Size
The following are the different methods to change/increase the JVM Heap size:
Command Line Method
This sets the initial heap size to 256MB and the maximum heap size to 1024MB:
java -Xms256m -Xmx1024m MyApplication
Set the initial and maximum heap size to 1GB, and the young generation size to 256MB:
java -Xms1024m -Xmx1024m -Xmn256m MyApplication
Common Unit Specifiers:
- k or K for kilobytes (e.g., 256k)
- m or M for megabytes (e.g., 512m)
- g or G for gigabytes (e.g., 2g)
Environment Variables
For Windows, in the environment variables, set the size according to below:
set JAVA_OPTS=-Xms1024m -Xmx2048m
For Linux/Unix, in the environment variables, set the size according to below:
export JAVA_OPTS="-Xms1024m -Xmx2048m"
IDE Configuration
For the Eclipse IDE, follow the following steps:
- Go to Run->Run Configurations
- Select your Java application
- Arguments tab-> VM arguments: -Xms512m -Xmx2048m
Example
Below is an example for monitoring the heap usage in Java:
public class HeapSizeTest { public static void main(String[]args){ // To get the JVM Heap Size long heapSize = Runtime.getRuntime().totalMemory(); // To print the JVM Heap Size System.out.println("Heap Size: " + heapSize); } }
Output
Heap Size: 16252928