2455. Java Advanced — JVM Parameters JVM Parameters
Most well-known options for JVM configuration.
1. Memory
1.1 Explicit Heap Memory – Xms and Xmx Options
- unit can be marked as g for GB, m for MB and k for KB.
Example: Assign minimum 2 GB and maximum 5 GB to JVM.
1.2 Handling Out of Memory
Dump heap memory into a physical file for analyzing the memory leak.
- HeapDumpOnOutOfMemoryError instructs the JVM to dump heap into physical file in case of OutOfMemoryError
- HeapDumpPath denotes the path where the file is to be written; any filename can be given; however, if JVM finds a
tag in the name, the process id of the current process causing the out of memory error will be appended to the file name with .hprof format
2. Garbage Collection
2.1 Garbage Collection Algorithm
Choosing a right Garbage Collection algorithm is critical for better stability of the application. JVM has four types of GC implementations:
- Serial Garbage Collector
- Parallel Garbage Collector
- CMS Garbage Collector
- G1 Garbage Collector
These implementations can be declared with the below parameters:
2.2 GC Logging
Monitor the JVM’s Garbage Collection performance by logging the GC activity.
- UseGCLogFileRotation specifies the log file rolling policy, much like log4j, s4lj, etc.
- NumberOfGCLogFiles denotes the max number of log files that can be written for a single application life cycle.
- GCLogFileSize specifies the max size of the file.
- loggc denotes its location.
Example: Assign a maximum of 100 GC log files, each having a maximum size of 50 MB and want to store them in ‘/home/user/log/’ location.
Let’s talk about Java/JVM flags
![]()
Why would you want to know this? Well, in order to be able to tune an application and identify performance issues it’s important to understand what flags are actually being used by your application and possibly why.
TL;DR
You can view the flags used in your java application in multiple ways. Either by specifying a flag on the command line (-XX:+PrintFlagsFinal) or by using jcmd or jinfo on an active VM.
I’m running OpenJDK 13, in case you get different results please consult your specific JVM implementations documentation. Most of what is written here applies to other java versions as well.
Process ID
Most commands to monitor an active JVM requires that you identify the process id (PID) of the application. A simple way to retrieve the PID is using JPS [1] but you can also retrieve it from code if needed. Here I have started a simple program that loops forever called JavaFlags.
If you want to retrieve it by code take a loop at the example below which illustrates how to get the PID of the current process and other processes started with the java command.
Which provides the following output.
Now that we got the PID we are able to use other java tools to get more information about the running JVM. This article will talk about how to figure out what arguments was provided to the JVM and from where. Future articles will talk about how to actually monitor and investigate possible issues and tune the application.
View flags
There are in fact multiple ways you can retrieve the flags of an active JVM.
Side note
It is possible to tell the JVM to print the flags it uses on startup using a jvm flag but here we assume that this flag was not provided. I have included it below for those who are interested.
To get information about this JVM and its flags you can run the following command.
Show all
The following command prints the same information as the aforementioned flag using jcmd of an active VM [2].
The first brackets can contain lots of different values, below are some of the most common.
- product: The default value of this flag is the same across all platforms, in other words, it’s a product build default value.
- pd product: The default value of this flag is platform dependent (e.g. linux-x64)
- manageable: The value of this flag can be set during runtime. For instance using jinfo as explained below [3].
- C1|C2 product: The default value of this flag is specific to C1 (client) and C2 (server) JIT compiler. The difference between these compilers is out of scope of this article. Shortly, client compiler runs faster but produces less optimized code than C2. Which one is used depends on your platform but can be overridden in some instances, on most machines today both are used due to tiered compilation being the default since java 8.
- C1|C2 diagnostic: The flag provides diagnostic info and is not used for tuning.
- ARCH product: The flag only exists for some architectures and constant for others.
- lp64_product: The flag only exists for 64-bit JVM and is constant for 32-bit versions.
- commercial: The flag is only available for commercial version.
- experimental: The flag is available if experimental mode is specified using -XX:+UnlockExperimentalVMOptions
The second brackets can be one of the following. Note that in previous versions, this bracket was not there and instead it was specified if the flag had a non-default value with a colon before the equal sign (“:=”).
- : The value for this flag is a default value for this JVM version.
- : The value was set to an optimal value according to the JVM taking into account the specific machine it is running on (e.g. OS, 32/64-bit or number of CPU:s).
- : The flag was set on the command line which always takes precedence (if a flag is specified multiple times, the last occurrence is used).
- : The flag was changed during runtime, only applicable for manageable flags.
Show specific flag
You can also view the current value of a flag using jinfo like this.
Setting flags
The most common way of setting flags is on the command line. The syntax differs depending on if it’s a boolean or a value flag.
Boolean examples
Value examples
Setting a flag during runtime
You can also set some flags (if they are specified as manageable) during runtime. First get the PID as explained above then you can run the following command. If you try and set a non-manageable flag you will get an error (on earlier versions I believe this was silently ignored).
Boolean examples
Value examples
Note here that you cannot use a unit such as K, M, or G but you have to specify the exact value.
Finally, some flags have aliases and can be specified by either or. For instance setting the maximum heap size.
The only issue with this is that jinfo will not recognize one of the alises, for the case above using Xmx you will get an not found error.
More information about this and other flags can be found here and here [4, 5].
Какие параметры используются для настройки jvm java 8
Please note that this page only applies to JDK 7 and earlier releases. For JDK 8 please see the Windows, Solaris reference pages.
This document provides information on typical command-line options and environment variables that can affect the performance characteristics of the Java HotSpot Virtual Machine. Unless otherwise noted, all information in this document pertains to both the Java HotSpot Client VM and the Java HotSpot Server VM.
Categories of Java HotSpot VM Options
- Options that begin with -X are non-standard (not guaranteed to be supported on all VM implementations), and are subject to change without notice in subsequent releases of the JDK.
- Options that are specified with -XX are not stable and are subject to change without notice.
Users of JDKs older than 1.3.0 who wish to port to a Java HotSpot VM, should see Java HotSpot Equivalents of Exact VM flags.
Some Useful -XX Options
Default values are listed for Java SE 6 for Solaris Sparc with -server. Some options may vary per architecture/OS/JVM version. Platforms with a differing default value are listed in the description.
Java Blog
Если вы являетесь Java-разработчиком или администратором Java приложения, вам поможет в работе знание того, что означают опции JVM, а также их важность и как они влияют на ваше приложение.
Обзор параметров JVM
Если говорить о параметрах JVM, то есть три типа параметров, которые вы можете включить в JVM: стандартные, нестандартные и расширенные параметры. Если вы используете расширенную опцию, вы всегда используете опцию с -XX. Точно так же, если вы применяете нестандартную опцию, вы используете -X. Стандартные опции ничего не добавляют к опции.
Какие параметры JVM используются вашим приложением?
Если приложение работает в Linux, вы можете использовать
для идентификации процесса Java и просмотра параметров JVM, напечатанных как аргументы процесса. Если в системе выполняется более одного Java-процесса, вам может потребоваться использовать ключевое слово, уникальное для вашего Java-приложения.
Если ваш аргумент слишком длинный, попробуйте использовать
так как эта команда также покажет длинный список аргументов.
Имея список флагов JVM, вы можете получить представление о поведении любого Java-приложения, например Tomcat.
1. Размер кучи (heap) Java
-Xms — эта опция определяет начальный размер кучи для JVM, например, Xms2048m, что означает, что начальный размер кучи JVM составляет около 2 ГБ. Итак, когда JVM запускается, куча памяти будет очень большой. Это делается для предотвращения изменения размера во время запуска и увеличения времени запуска JVM.
-Xmx — этот параметр определяет максимальный размер кучи JVM, например, Xmx2048m, что означает, что максимальный размер кучи JVM будет составлять только 2 ГБ.
По сути, вы всегда будете иметь -Xms и -Xmx вместе.
2. Задание процента кучи
-XX:MaxHeapFreeRatio — устанавливает максимальный процент свободного пространства кучи после GC (Garbage Collecting, сборки мусора), чтобы избежать сжатия.
-XX:MinHeapFreeRatio — устанавливает минимальный процент свободного пространства кучи после GC, чтобы избежать расширения; для мониторинга использования кучи вы можете использовать JConsole.
3. Включить обмен данными класса
Укажите опцию Xshareclasses, чтобы включить общий доступ к данным класса в общем кэше классов. JVM подключается к существующему кэшу или создает кэш, если он не существует. У вас может быть несколько кэшей, и вы можете указать правильный кэш, добавив подопцию в опцию -Xshareclasses.
4. PermGen размер
Ранее параметры JVM определяли размер кучи памяти, но -XX:PermSize — для определения размера пространства PermGen, в котором сохраняются пул строк и метаданные класса. Этот параметр особенно эффективен для веб-сервера, такого как Tomcat, который часто загружает классы веб-приложения во время развертывания.
Кстати, стоит понимать, что пространство PermGen занято Metaspace в Java 8, и этот параметр неприменим, если вы работаете с JRE 8 JVM.
5. Распечатать GC (Garbage Collector)
Эти параметры JVM используются для включения ведения журнала сбора мусора, что очень эффективно для чувствительной к задержке операции. Обычно работа идет в системах, где ведется поиск задержек в микросекундах, но большая сборка мусора может длиться несколько миллисекунд.
Эта удобная опция подскажет вам важную статистику GC. Станет известно, будет ли это большая или небольшая сборка мусора, какой тип сборщика мусора применяется, как часто восстанавливается память, сколько времени он занимал и т.д.
6. Обработка ошибки «OutOfMemory»
Чтобы вызвать дамп кучи при нехватке памяти, вы можете использовать -XX:+HeapDumpOnOutOfMemoryError
Эта опция JVM создает дамп стека, когда ваша JVM завершается с ошибкой OutOfMemory. Там нет никаких затрат, если ошибка OutOfMemory действительно не происходит. Этот флаг является обязательным для производственных систем, поскольку обычно это единственный способ глубоко определить проблему.
Дамп кучи будет установлен в «текущем каталоге» JVM по умолчанию. Если вы хотите создать дамп кучи в определенном каталоге, запустите
Файл дампа кучи может быть огромного размера, вплоть до гигабайт, поэтому убедитесь, что целевая файловая система обеспечивает достаточную емкость.
Если мы хотим перезапустить сервер сразу после возникновения нехватки памяти, мы можем установить этот параметр с той же целью:
7. Trace загрузки классов и выгрузки
-XX:+TraceClassLoading и -XX:+TraceClassUnloading — это две опции JVM, которые мы используем для печати информации журналов всякий раз, когда классы загружаются в JVM или выгружаются из JVM. Эти флаги JVM полезны, если у вас есть какой-либо тип утечки памяти, связанный с загрузчиком классов и есть подозрение, что классы не выгружаются или не собирается мусор.
8. Java classpath (путь к классу)
Говоря о Java Classpath а затем -Xbootclasspath определяет записи classpath, которые мы хотим загрузить без проверки. JVM проверяет все классы, которые она загружает, чтобы убедиться, что она не пытается разыменовать объект с помощью int, выталкивает дополнительные записи из стека или выталкивает слишком много, и так далее.
Помещение class в bootclasspath также снижает стоимость, но его следует использовать только тогда, когда вы знаете, что классы проверялись много раз раньше. В JRuby это сократило время запуска вдвое и более для простого скрипта.
9. Профилирование
Java профилирование — это процесс мониторинга различных параметров уровней JVM, таких как выполнение методов, выполнение потоков, сборка мусора и создание объектов. Java профилирование обеспечивает более точное представление о выполнении целевого приложения и использовании его ресурсов.
10. 64-битная среда
В среде ОС, в которой установлены 32- и 64-разрядные пакеты, JVM автоматически выбирает 32-разрядные пакеты среды по умолчанию.
Если мы хотим установить 64-битную среду вручную, мы можем сделать это с помощью параметра -d . OS bit может быть 32 или 64.