The Java Virtual Machine (JVM) has two memory-related options or flags, namely “-Xmx” and “-Xms”. When running a Java application, the Java Virtual Machine utilizes the “-Xmx” option to set the maximum heap size and the “-Xms” option to set the initial heap size.
In java, memory allocation for the heap size using -Xmx and –Xms options is specified in either megabytes (M) or gigabytes (G), based on the value appended to these options.
Let’s delve into both flags or options thoroughly to better comprehend troubleshooting memory-related errors.
What is -Xmx in java?
- It Sets the maximum heap size.
- The Default value for the maximum heap size is often around 1/4th to 1/3rd of the physical memory.
- The Xmx format is as follows:
java -Xmx{Numerical Size}{Unit}
What is -Xms in java?
- It Sets the minimum heap size.
- The Default value for the maximum heap size is often around 1/64th to 1/4th of the physical memory.
- The Xms format is as follows:
java -Xms{Numerical Size}{Unit}
Note – Generally the numerical size represents A whole number and by default the memory size is in bytes.
Example:
# Start with 128MB of memory, and allow the Java process to use up to 1024MB of memory.
java -Xms128m -Xmx1024m
# Start with 256MB of memory, and allow the Java process to use up to 4G (4096MB) of memory.
java -Xms256m -Xmx4g
The memory unit can be represented in either uppercase or lowercase letters: ‘M’ or ‘m’ for megabytes, and ‘G’ or ‘g’ for gigabytes. For example: “-Xmx10G” and “-Xmx10g” do the exact same thing.
Note that the memory size must be in multiples of 1024 and must be greater than 2MB and there is no space between the flags and the memory size. Also If you do not add a unit while setting up the memory size, then the result will be in bytes as the default unit is bytes. for example: consider 64 as 64 bytes, not 64 megabytes or 64 kilobytes.