- What are Xmx and Xms parameters in java
- What are -Xms and -Xms parameters in Java/JVM (Updated up to Java 13)
- Default Java Xmx and Xms Values
- Java 13 and the Z Garbage Collector
- Параметры -Xms и -Xmx при запуске JVM
- Что такое -Xms и -Xmx ?
- Пример использования
- Значения по умолчанию
- Заключение
- Xms and Xmx Java
- What are “Xms” and “Xmx” in Java?
- -Xms
- -Xmx
- Important Considerations
- Examples
- Conclusion
- About the author
- Umar Hassan
What are Xmx and Xms parameters in java
In this post, we will see about Xms and Xmx parameter in java.
-Xmx specifies maximum memory size for Java virtual machine (JVM), while -Xms specifies the initial memory size.
It means JVM will be started with Xms amount of memory and JVM will be able to use maximum of JVM amount of memory.
Let’s understand this with help of example.
So java process will start with 512 MB of memory heap and can use upto 1024 MB of memory heap.
-Xmx and -Xms can be defined in different size such as kilobytes, megabytes and gigabytes.
If Java process exceeds -Xmx memory size, then you will java.lang.OutOfMemoryError .
Default initial size is allocated on the based of ergonomics algorithm.
-Xms and -Xmx are the options for JVM’s heap and JVM can use more memory than size allocated to heap.
If you want to learn about all -X option, you can use java -X command.
Apples-MacBook-Pro-5:~ apple$ java -X-Xbatch
disable background compilation-Xbootclasspath/a:
append to end of bootstrap class path
-Xcheck:jni
perform additional checks for JNI functions
-Xcomp
forces compilation of methods on first invocation
-Xdebug
provided for backward compatibility
-Xdiag
show additional diagnostic messages
-Xfuture
enable strictest checks, anticipating future default
-Xint
interpreted mode execution only
-Xinternalversion
displays more detailed JVM version information than the
-version option
-Xloggc:
log GC status to a file with time stamps
-Xmixed
mixed mode execution (default)
-Xmn
sets the initial and maximum size (in bytes) of the heap
for the young generation (nursery)
-Xms
set initial Java heap size
-Xmx
set maximum Java heap size
-Xnoclassgc
disable class garbage collection
-Xrs
reduce use of OS signals by Java/VM (see documentation)
-Xshare:auto
use shared class data if possible (default)
-Xshare:off
do not attempt to use shared class data
-Xshare:on
require using shared class data, otherwise fail.
-XshowSettings
show all settings and continue
-XshowSettings:all
show all settings and continue
-XshowSettings:locale
show all locale related settings and continue
-XshowSettings:properties
show all property settings and continue
-XshowSettings:vm
show all vm related settings and continue
-XshowSettings:system
(Linux Only) show host system or container configuration and continue
-Xss
set [java thread](https://java2blog.com/java-thread-example/ “java thread”) stack size
-Xverify
sets the mode of the bytecode verifier
–add-reads =(,)*
updates to read , regardless
of module declaration.
can be ALL-UNNAMED to read all unnamed
modules.
–add-exports /=(,)*
updates to export to ,
regardless of module declaration.
can be ALL-UNNAMED to export to all
unnamed modules.
–illegal-access=
permit or deny access to members of types in named modules
by code in unnamed modules.
is one of “deny”, “permit”, “warn”, or “debug”
This option will be removed in a future release.
–limit-modules [,…]
limit the universe of observable modules
–patch-module =(:)*
override or augment a module with classes and resources
in JAR files or directories.
–[email protected]
disable further argument file expansion
–source
set the version of the source in source-file mode.
These extra options are subject to change without notice.
The following options are Mac OS X specific:
-XstartOnFirstThread
run the main() method on the first (AppKit) thread
-Xdock:name=
override default application name displayed in dock
-Xdock:icon=
override default icon displayed in dock
The -X options are non-standard and subject to change without notice.
Please note that it is quite important to set -Xms and -Xmx parameters correctly. Java 13 has introduced a new feature in Z garbage collector where it will uncommit the memory to CPU but it won’t uncommit below -Xms parameter, so if you put -Xms and -Xmx as equal, it will basically disable this feature. This feature is quite useful where memory footprint is a concern.
That’s all about Java’s -Xmx and -Xms parameters.
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.
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-приложений. Однако следует помнить, что задание слишком большого объема памяти может привести к неэффективному использованию ресурсов и замедлению работы всей системы.
Xms and Xmx Java
While creating application(s), there can be a requirement where the programmer needs to enhance the performance and memory. In such case scenarios, the “Xms” and “Xmx” parameters play a vital role in manipulating the heap size utilized by Java Virtual Machine. These parameters can be stated in various formats like KB, MB, etc.
This write-up will illustrate the usage of the “Xms” and “Xmx” parameters in Java.
What are “Xms” and “Xmx” in Java?
“Xms” and “Xmx” in Java refer to the parameters that are utilized to adjust the heap size. It works in such a way that the former parameter allocates the minimum heap size and the latter parameter assigns the maximum heap size.
-Xms
It is utilized to set the initial heap size. Allocating the minimum heap size identical to the maximum heap size is advised to refrain from garbage collection.
-Xmx
It is used to assign the maximal heap size. The performance is affected if the maximum heap value is allocated lower compared to the amount of live data.
Syntax | Usage | Default |
-Xms | Allocates the minimum heap size. | 8 MB |
-Xmx | Allocates the maximal heap size. | 25% of available/free memory |
Important Considerations
The following points should be considered before working with the discussed parameters:
- If “-Xms” is allocated greater than “-Xmx”, the VM fails and will log the following message “-Xms too large for -Xmx”.
- In the other case, if the limit set by the “-Xmx” parameter is exceeded, the VM gives an “OutofMemory” limitation.
Examples
The following examples cover all the possible outcomes of the discussed parameters:
The given command indicates that the heap starts from “4” MB till the maximum of “64” MB.
The above size signifies that the heap starts from “50” MB till the default maximum.
Likewise, here the heap initiates from the default initial value till a maximum of “256” MB.
The above sizes state that the heap initiates at “50” MB and remains intact, thereby never growing.
Conclusion
The “-Xms” and “-Xmx” parameters in Java assign the minimum and the maximum heap sizes, respectively and the heap can never grow larger than “-Xmx”. Also, these parameters are recognized by the Java virtual machine (JVM). This blog discussed the functionalities of the “-Xms” and “-Xmx” parameters in Java.
About the author
Umar Hassan
I am a Front-End Web Developer. Being a technical author, I try to learn new things and adapt with them every day. I am passionate to write about evolving software tools and technologies and make it understandable for the end-user.