Using -Xms and -Xmx parameters in Java

January 04, 2020 No comments java memory heap

1. Introduction

This article describes how to use -Xms and -Xmx parameters in Java applications. It explains in a simple words what is a Java Heap and how to increase its size in order to avoid the java.lang.OutOfMemoryError exceptions.

2. Java Heap

Java Heap is an amount of memory allocated for Java applications running on the JVM. This is a special place where all Java Objects are being held and can be shared between threads. For Garbage Collection Java Heap is a workplace, where it search for references of objects ready to be removed from a memory.

The Java Heap Size of Java applications can be changed, we use -Xms and -Xmx parameters to control it.

  • -Xms - is a initial Java heap size,
  • -Xmx - is a maximum Java heap size.

In the following example we start FrontBackEndApplication with initial Java Heap Size set to 512MB and a maximum Java Heap Size set to 1024MB.

java -Xms512m -Xmx1024m FrontBackEndApplication

In other words, we allow FrontBackEndApplication to consume up to 1024MB of memory. However, if this value will be somehow insufficient, it will cause the java.lang.OutOfMemoryError: Java heap space exception. This situation could happen in heavy applications or as a result of the memory leak.

3. Choose the best Java Heap Size

If you face the problem of choosing the most optimal Java Heap Size, just keep in mind that:

1) Large Java Heap Size will takes longer to fill and allows the application to run longer between GC (Garbage Collection) events, but cleaning memory will be very timeconsuming,

2) Small Java Heap Size holds fewer objects and needs frequent GC events to clear the memory, also may lead to out-of-memory errors.

According to the ergonomics documentation Java used the following algorithm to calculate optimal Heap size:

  • Initial heap size of 1/64 of physical memory up to 1 GB,
  • Maximum heap size of 1/4 of physical memory up to 1 GB.

4. Conclusion

In this article, we explained two parameters -Xmx and -Xms used to control the initial and a maximum Java Heap Size - the memory that Java application can use for holding Objects. We should balance between too large and too small maximum Java Heap Size to avoid OutOfMemory exceptions and in other hand to give GC optimal working environment.

{{ message }}

{{ 'Comments are closed.' | trans }}