Java jar xmx xms

What are -Xms and -Xms parameters in Java/JVM (Updated up to Java 13)

These are Java Virtual Machine (JVM) parameters that are used to specify memory boundaries for Java applications. They are often used when troubleshooting performance issues or OutOfMemoryErrors. They control the amount of memory that is available to a Java application. The Xmx parameter specifies the maximum memory an app can use, where as Xms specifies the minimum or the initial memory pool. If your application exceeds the maximum memory (allocated using the Xmx ) and the garbage collector cannot free up memory, the JVM will crash with a OutOfMemoryError. If you’re interested, I wrote an article explaining with examples how garbage collection works and its generations.

 $ java -Xmx256m Xmx1024m -jar yourapp.jar 

In the example above, the application yourapp.jar will get an initial memory pool of 256 megabytes and a maximum up to 1024 megabytes. In 256m , the m stands for megabytes. You can use g or G to indicate gigabytes.

  • Xmx1g or Xmx1G : Set the maximum memory size to 1 gigabytes.
  • Xmx1024m or Xmx1024M : Set the maximum memory size to 1024 megabytes.
  • Xmx1024000k or Xmx1024000K : Sets the maximum memory size to 1024000 kilobytes.

It’s important to note that both Xmx and Xms are optional. If these are not provided, the Java Virtual Machine (JVM) will use default values for them.

Читайте также:  Java граф поиск пути

Default Java Xmx and Xms Values

The default values vary and depend on different factors. It depends on the amount of physical memory of the system, JVM mode (e.g. -server vs -client ) and other factors like JVM implementation and version. Typically, the default values are calculated as follows:

  • Initial heap size of 1/64 of physical memory (for Xms )
  • Maximum heap size of 1/4 of physical memory (for Xmx )

An easy way to determine the default settings is to use the Print Flags option. It will show xms (InitialHeapSize) and xmx (MaxHeapSize) in bytes. You’ll need to convert manually to MB or GB.

java -XX:+PrintCommandLineFlags -version 

On my machine (Macbook Pro with 8 GB of memory) I got the following output:

-XX:InitialHeapSize=134217728 -XX:MaxHeapSize=2147483648 -XX:+PrintCommandLineFlags -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseParallelGC 

So on my machine with 8 GB of total physical memory, I get:

  • Xms (InitialHeapSize): 134217728 bytes or 134 MB (~ roughly 1/64th of 8 GB)
  • Xmx (MaxHeapSize): 2147483648 bytes or 2 GB (~ roughly 1/4th of 8 GB)

You can specify either Xms, Xmx or both. If you don’t specify either one of them, the default value will be used. In the example below, the maximum memory will be limited to 1024 megabytes. The initial memory will use the default value.

 java -Xmx1024m -jar yourapp.jar 

Here’s a good YouTube video that walks through the process of troubleshooting memory related errors and shows to fix them using examples.

Java 13 and the Z Garbage Collector

Java 13 introduced a new garbage collector called ZGC. One of its features includes an optimization to return un-used memory to the operating system. This feature is enabled by default and it will not return memory such that heap size shrinks below Xms . So if you’re setting Xms to equal Xmx (as many developers do,) it will essentially disable the feature.

If you want to see all available JVM parameters, you can use the java -X switch e.g.

$ java -X -Xmixed mixed mode execution (default) -Xint interpreted mode execution only -Xbootclasspath: set search path for bootstrap classes and resources -Xbootclasspath/a: append to end of bootstrap class path -Xbootclasspath/p: prepend in front of bootstrap class path -Xdiag show additional diagnostic messages -Xnoclassgc disable class garbage collection -Xincgc enable incremental garbage collection -Xloggc: log GC status to a file with time stamps -Xbatch disable background compilation -Xms set initial Java heap size -Xmx set maximum Java heap size -Xss set java thread stack size -Xprof output cpu profiling data -Xfuture enable strictest checks, anticipating future default -Xrs reduce use of OS signals by Java/VM (see documentation) -Xcheck:jni perform additional checks for JNI functions -Xshare:off do not attempt to use shared class data -Xshare:auto use shared class data if possible (default) -Xshare:on require using shared class data, otherwise fail. -XshowSettings show all settings and continue -XshowSettings:all show all settings and continue -XshowSettings:vm show all vm related settings and continue -XshowSettings:properties show all property settings and continue -XshowSettings:locale show all locale related settings and continue The -X options are non-standard and subject to change without notice. 

Источник

Параметры -Xms и -Xmx при запуске JVM

Часто при работе с Java разработчики сталкиваются с такими параметрами запуска JVM, как -Xms и -Xmx . Они отвечают за управление памятью в виртуальной машине Java и могут существенно повлиять на производительность и стабильность работы приложения.

Что такое -Xms и -Xmx ?

Параметр -Xms задает начальный размер (в байтах) кучи, которую JVM выделяет при старте приложения. Это важно, поскольку недостаток памяти при старте может привести к тому, что приложение будет работать медленно или вообще не сможет запуститься.

Параметр -Xmx , наоборот, задает максимальный размер (также в байтах) кучи. Если приложение пытается использовать больше памяти, чем задано параметром -Xmx , то JVM может выбросить исключение OutOfMemoryError .

Пример использования

java -Xms128m -Xmx1024m MyApplication

В этом примере при запуске приложения MyApplication виртуальная машина Java выделит начально 128 мегабайт памяти, а максимальный размер кучи составит 1024 мегабайт (или 1 гигабайт).

Значения по умолчанию

Значения параметров -Xms и -Xmx по умолчанию зависят от конкретной реализации JVM и могут варьироваться. Обычно начальный размер кучи составляет несколько десятков мегабайт, а максимальный — от половины до четверти от всего доступного объема оперативной памяти.

Заключение

Правильное использование параметров -Xms и -Xmx может существенно улучшить производительность и стабильность работы Java-приложений. Однако следует помнить, что задание слишком большого объема памяти может привести к неэффективному использованию ресурсов и замедлению работы всей системы.

Источник

Оцените статью