Explain Codes LogoExplain Codes Logo

How to set the maximum memory usage for JVM?

java
memory-management
jvm-configuration
performance-tuning
Alex KataevbyAlex Kataev·Feb 21, 2025
TLDR

In a nutshell, to limit JVM's heap size, the -Xmx command followed by your desired memory cap is your best bet. For instance, for a 1GB limit, here's your command:

java -Xmx1g -jar YourApp.jar

The heap size of your Java application is now effectively restricted at 1 gigabyte. The value 1g is flexible and can be adjusted to meet your memory limit requirements.

Figuring out JVM Memory: The Basics and Beyond

Setting the Memory Boundary with -Xms and -Xmx

Upon initializing a JVM, setting a minimum limit to the heap size can be done with -Xms, which the JVM reserves at startup. The -Xmx parameter functions to assign the maximum heap size that the JVM can allocate. Notation-wise, use M for megabytes and G for gigabytes for an intuitive feel:

// Let's kick this JVM off with a min heap size of 256M, and a max heap size of 2G (just like my old thumb drive)! java -Xms256M -Xmx2G -jar YourApp.jar

Rolling with the Native Memory Allocation

The JVM utilizes memory in several areas — the heap, the Metaspace, thread stacks, and direct memory buffers fall under this umbrella. The native heap size can be defined and modified with -XX:MaxDirectMemorySizeif not specified, it defaults to a modest 128M:

// Our space, our rules! Time to boost my native heap to 512MB (size does matter!) java -XX:MaxDirectMemorySize=512m -jar YourApp.jar

Using ulimit to Control Total Memory Overhead

For Unix user-friends, the formidable ulimit command can administer the total memory of the JVM process preventing your Java application from becoming a system resource black hole:

ulimit -v 2097152 // Limiting to 2GB of memory for all the processes, JVM is no exception. java -jar YourApp.jar

Caution! This impacts all processes running, not just our JVM friend.

Memory Management: Tips & Tricks

Evaluating The Context:

Setting a memory limit might behave differently based on the platform and system dependencies. Keep in mind the host environment and other concurrently running apps when deciding on memory limits.

Digging into Stack Memory:

For applications that heavily use recursion, consider fine-tuning stack memory. Monitor with -Xss.

Monitor and Troubleshoot:

Leverage diagnostic tools like VisualVM in real-time to understand memory consumption. This will help optimize memory usage based on actual runtime data.

Mastering Garbage Collection:

For applications with large heap sizes, using particular garbage collectors, such as -XX:+UseG1GC can enhance memory management efficiency.