Core Java

-Xms and -Xmx parameter

Hello. In this tutorial, we will understand Xms and Xmx parameters in the java programming language.

1. Introduction

Heap space in java is the one created by the JVM when it starts and is slower than the stack memory. It is not thread-safe and is not automatically deallocated. It is used by the applications and it can be broken down into smaller parts called generations i.e.

  • Young generation
  • Old generation
  • Permanent generation – In java8 this is replaced by the Metaspace

The garbage collector is brought into the picture to free up the unused objects and provide sufficient memory for running the applications. There is no definitive number for the default heap size however in general cases it is 1/6th of the machine’s physical memory and if an object requires more memory than the available heap, the application will encounter the OutOfMemoryError on runtime. The java heap size is determined by the two parameters i.e.

  • -Xms: To set the initial heap size
  • -Xmx: To set the maximum heap size

The java -x command is used to list the different options.

2.1 How to use -Xms and -Xmx parameter

To use either of the parameters we need to use the java command as shown.

Command 1

java -Xmx4g -classpath ".:${CLASSPATH}" ${PROGRAM_NAME}

The above command will specify the maximum heap size for the program as 4GB. Similarly, you can use the -Xms command to specify the initial heap size. The below command will specify the initial heap size for the program as 128MB.

Command 2

java -Xms128m -classpath ".:${CLASSPATH}" ${PROGRAM_NAME}

2.2 Exceeding the -Xmx size

If the java process exceeds the -Xmx then java.lang.OutOfMemoryError is thrown by the program on runtime. In the current java paradigm, an error like the below is thrown by the applications, and to mitigate the issue one needs to increase the Metaspace size by adding the -XX:MaxMetaspaceSize flag to the startup parameters of the java application.

Error log snippet

OutOfMemoryError: Metaspace error is thrown

That is all for this tutorial and I hope the article served you with whatever you were looking for. Happy Learning and do not forget to share!

3. Summary

In this tutorial, we discussed the -Xmx and -Xms parameters in java and ways to implement it. The parameters are used to increase the max java heap size or the initial java heap size.


An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Notify of

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Inline Feedbacks
View all comments
Back to top button