Компиляция в Java

Программирование в IDE — прекрасно: связанность зависимостей кода, удобный дебаг, понятное тестирование, темная тема. Так вот, благодаря IDE разработка развивается семимильными шагами. Но она расслабляет. С каждым днем, погружаясь в функционал IDE, разработчик привыкает к коммиту одной кнопкой или сборке двумя кликами. Гораздо хуже обстоит ситуация с новичками в программировании, которые с самого начала работают в IDE, игнорируя работу в командной строке. Например, в Intellij IDEA компиляция Java приложения демонстрируется загрузочным баром в нижней панели, а все параметры компиляции, обработка classpath и прочих прелестей Java-жизни остается за кадром. Предлагаем поговорить о компиляции в Java без IDE. Для запуска примеров в статье следует убедиться, что на вашей машине установлена JDK 1.7 и старше.
Как скомпилировать программу?
- Есть исходный код в файле с именем НазваниеКласса.java;
- Если в коде нет ошибок, он компилируется в байт-код (в файл НазваниеКласса.class);
- Программа запускается.
Для чего нужна команда javac

Окей, первый пункт выполнен. Идем дальше, чтобы понять: скомпилировать — это как? 🙂 В этом нам поможет команда javac, в аргументе которой необходимо указать нужный файл: Если нет ошибок в коде, рядом с файлом Test.java появится файл Test.class. Это и есть скомпилированный байт-код. Теперь его нужно запустить. Здесь используется команда java, запускающая байт-код: На скриншоте видно, что в выводе получаем какие-то иероглифы: очевидно, это сбитая кодировка. Как правило это происходит в системе Windows. Для корректного отображения кириллицы в консоли, есть следующие команды: Они меняют текущую кодовую страницу командной консоли на время работы текущего окна. Попробуем еще раз: Это говорит приложение из командной строки. Знать принцип работы команды javac очень полезно, так как эта команда лежит в основе любой системы сборки проектов.
Компиляция и выполнение нескольких классов
Создание JAR-файлов
Компиляция в Java без IDE: обзор систем сборок
Как скомпилировать Java?
- mkdir — создание директорий
- delete — удаление файлов и директорий
- javac — компиляция Java–кода
- java — запуск скомпилированного кода
Maven

Maven предлагает несколько другой подход к сборке проектов. Здесь разработчик скорее описывает свой проект и дополнительные инструменты, которые использует, в отличие от Ant, где сборка — это последовательность действий. Maven популярен среди разработчиков благодаря простому управлению зависимостями и удобной интеграции со всеми средами разработки. При работе с Maven придерживаются такой структуры проекта: Правила сборки, зависимости и прочее описывается в файле pom.xml. Как правило он находится в главной папке проекта. При запуске Maven проверяет структуру и синтаксис файла, предупреждая об ошибках. В главной директории рядом с папками bin и src создаем файл pom.xml, внутрь добавляем: Далее в командной строке выполняем команду mvn: Теперь в папке bin есть папка src, в которой находятся скомпилированные классы. В pom.xml в теге build определена цель сборки — компиляция, директории файлов исходного кода и результата компиляции, а также имя проекта. У Maven есть множество целей сборки и плагинов для запуска тестирования, создания Jar-файлов, сборки дистрибутивов и других задач.
Работа с Java в командной строке
Сейчас уже никто не создает программы в консоли. Используя любимую IDE, разработчик чувствует себя неуютно за чужим компьютером, где её нет.
Решив разобраться в работе Ant и Maven, я поймал себя на том, что не смогу собрать приложение без них в консоли.
В данной статье я постарался уместить все этапы проектирования демонстрационного приложения, чтобы не искать справку по каждой команде на просторах Интернета.
От простого к .
Каждая программа обычно содержится в отдельном каталоге. Я придерживаюсь правила создавать в этом каталоге по крайней мере две папки: src и bin. В первой содержатся исходные коды, во второй — результат компиляции. В данных папках будет структура каталогов, зависящая от пакетов.
Один файл
Можно сделать и без лишних папок.
Берем сам файл HelloWorld.java.
Переходим в каталог, где лежит данный файл, и выполняем команды.
В данной папке появится файл HelloWorld.class. Значит программа скомпилирована. Чтобы запустить
Отделяем бинарные файлы от исходников
Теперь сделаем тоже самое, но с каталогами. Создадим каталог HelloWorld и в нем две папки src и bin.
Компилируем
Здесь мы указали, что бинарные файлы будут сохраняться в отдельную папку bin и не путаться с исходниками.
Используем пакеты
А то, вдруг, программа перестанет быть просто HelloWorld-ом. Пакетам лучше давать понятное и уникальное имя. Это позволит добавить данную программу в другой проект без конфликта имен. Прочитав некоторые статьи, можно подумать, что для имени пакета обязательно нужен домен. Это не так. Домены — это удобный способ добиться уникальности. Если своего домена нет, воспользуйтесь аккаунтом на сайте (например, ru.habrahabr.mylogin). Он будет уникальным. Учтите, что имена пакетов должны быть в нижнем регистре. И избегайте использования спецсимволов. Проблемы возникают из-за разных платформ и файловых систем.
Поместим наш класс в пакет с именем com.qwertovsky.helloworld. Для этого добавим в начало файла строчку
В каталоге src создадим дополнительные каталоги, чтобы путь к файлу выглядел так: src/com/qwertovsky/helloworld/HelloWorld.java.
Компилируем
В каталоге bin автоматически создастся структура каталогов как и в src.
Если в программе несколько файлов
HelloWorld.java
Adder.java
Ошибка возникла из-за того, что для компиляции нужны файлы с исходными кодами классов, которые используются (класс Calculator). Надо указать компилятору каталог с файлами с помощью ключа -sourcepath.
Компилируем
Если удивляет результат
Есть возможность запустить отладчик. Для этого существует jdb.
Сначала компилируем с ключом -g, чтобы у отладчика была информация.
Отладчик запускает свой внутренний терминал для ввода команд. Справку по последним можно вывести с помощью команды help.
Указываем точку прерывания на 9 строке в классе Calculator
Запускаем на выполнение.
Чтобы соориентироваться можно вывести кусок исходного кода, где в данный момент находится курссор.
Узнаем, что из себя представляет переменная а.
Выполним код в текущей строке и увидим, что sum стала равняться 2.
Поднимемся из класса Adder в вызвавший его класс Calculator.
Удаляем точку прерывания
Можно избежать захода в методы, используя команду next.
Проверяем значение выражения и завершаем выполнение.
Хорошо бы протестировать
Запускаем. В качестве разделителя нескольких путей в classpath в Windows используется ‘;’, в Linux — ‘:’. В консоли Cygwin не работают оба разделителя. Возможно, должен работать ‘;’, но он воспринимается как разделитель команд.
Создадим библиотеку
Класс Calculator оказался полезным и может быть использован во многих проектах. Перенесем всё, что касается класса Calculator в отдельный проект.
Измените также назавания пакетов в исходных текстах. В HelloWorld.java нужно будет добавить строку
Делаем архив jar
С помощью ключа -C мы запустили программу в каталоге bin.
Надо узнать, что у библиотеки внутри
Можно распаковать архив zip-распаковщиком и посмотреть, какие классы есть в библиотеке.
Информацию о любом классе можно получить с помощью дизассемблера javap.
Из результата видно, что класс содержит кроме пустого конструктора, ещё один метод sum, внутри которого в цикле вызывается метод add класса Adder. По завершении метода sum, вызывается Adder.getSum().
Без ключа -c программа выдаст только список переменных и методов (если использовать -private, то всех).
Лучше снабдить библиотеку документацией
Изменим для этого класс калькулятора.
Документацию можно создать следующей командой. При ошибке программа выдаст список возможных опций.
В результате получиться следующее 
Можно подписать jar-архив
Если требуется подписать свою библиотеку цифровой подписью, на помощь придут keytool и jarsigner.
Генерируем подпись.
Генерируем Certificate Signing Request (CSR)
Содержимое полученного файла отправляем в центр сертификации. От центра сертификации получаем сертификат. Сохраняем его в файле (например, qwertokey.cer) и импортируем в хранилище
Файл qwertokey.cer отправляем всем, кто хочет проверить архив. Проверяется он так
Использование библиотеки
Есть программа HelloWorld, которая использует библиотечный класс Calculator. Чтобы скомпилировать и запустить программу, нужно присоединить библиотеку.
Компилируем
Собираем программу
Это можно сделать по-разному.
Первый способ
Здесь есть тонкости.
В строке
не должно быть пробелов в конце.
Вторая тонкость описана в [3]: в этой же строке должен стоять перенос на следующую строку. Это если манифест помещается в архив сторонним архиватором.
Программа jar не включит в манифест последнюю строку из манифеста, если в конце не стоит перенос строки.
Ещё момент: в манифесте не должно быть пустых строк между строками. Будет выдана ошибка «java.io.IOException: invalid manifest format».
При использовании команды echo надо следить только за пробелом в конце строки с main-class.
Второй способ
В данном способе избегаем ошибки с пробелом в main-class.
Третий способ
Включили код нужной библиотеки в исполняемый файл.
Запуск исполняемого jar-файла
Файл calculator.jar исполняемым не является. А вот helloworld.jar можно запустить.
Если архив был создан первыми двумя способами, то рядом с ним в одном каталоге должна находится папка lib с файлом calculator.jar. Такие ограничения из-за того, что в манифесте в class-path указан путь относительно исполняемого файла.
При использовании третьего способа нужные библиотеки включаются в исполняемый файл. Держать рядом нужные библиотеки не требуется. Запускается аналогично.
Как быть с приложениями JavaEE
Аналогично. Только библиотеки для компиляции нужно брать у сервера приложений, который используется. Если я использую JBoss, то для компиляции сервлета мне нужно будет выполнить примерно следующее
Структура архива JavaEE-приложения должна соответствовать определенному формату. Например
Способы запуска приложения на самом сервере с помощью командной строки для каждого сервера различны.
Надеюсь, данная статья станет для кого-нибудь шпаргалкой для работы с Java в командной строке. Данные навыки помогут понять содержание и смысл Ant-скриптов и ответить на собеседовании на более каверзные вопросы, чем «Какая IDE Вам больше нравится?».
Как запустить java файл через командную строку

Итак, после установки JDK создадим первое приложение на языке Java. Что необходимо для создания программы на Java? Прежде всего нам надо написать код программы, и для этого нужен текстовый редактор. Можно использовать любой текстовый редактор, например, Notepad++.
И чтобы превратить код программы в исполняемое приложение необходим компилятор. После установки JDK все файлы по умолчанию помещаются в каталог C:\Program Files\Java\jdk-[номер_версии] (при использовании ОС Windows). В моем случае это каталог C:\Program Files\Java\jdk-19 . Если мы откроем в нем подкаталог bin , то мы сможем увидеть в нем ряд утилит. Нас прежде всего интересует утилита компилятора javac . Чтобы скомпилировать класс программы, нам надо передать ее код этому компилятору.

Также следует отметить другую утилиту из этой папки — java.exe, которая позволяет запускать скомпилированную программу.
Итак, создадим на жестком диске какой-нибудь каталог, в котором будут располагаться файлы с исходным кодом на языке Java. Допустим, это будет каталог C:/Java . Затем создадим в этом каталоге текстовый файл, который переименуем в Program.java . Откроем этот файл в любом текстовом редакторе и наберем в нем следующую программу:
Java является объектно-ориентированным языком, поэтому вся программа представляется в виде набора взаимодействующих классов. В данном случае определен один класс Program.
При определении класса вначале идет модификатор доступа public , который указывает, что данный класс будет доступен всем, то есть мы сможем его запустить из командной строки. Далее идет ключевое слово class , а затем название класса. То есть класс называется Program. После названия в фигурных скобках расположено содержимое класса.
Класс может содержать различные переменные и методы. В данном случае у нас объявлен один метод main . Это главный метод в любой программе на Java, он является входной точкой программы и с него начинается все управление. Он обязательно должен присутствовать в программе.
Метод main также имеет модификатор public . Слово static указывает, что метод main — статический, а слово void — что он не возвращает никакого значения. Позже мы подробнее разберем, что все это значит.
Далее в скобках у нас идут параметры метода — String args[] — это массив args, который хранит значения типа String , то есть строки. В данном случае ни нам пока не нужны, но в реальной программе это те строковые параметры, которые передаются при запуске программы из командной строки.
После списка параметров в фигурных скобках идет тело метода — это собственно те инструкции, которые и будет выполнять метод. В данном случае фактически определени определена только одна инструкция — вывод на консоль некоторой строки. Для вывода на консоль используется встроенный метод System.out.println() . В этот метод передается выводимая строка. Каждая инструкция завершается точкой с запятой.
Теперь скомпилируем написанную программу. Откроем командную строку (в Windows) или терминал в Linux/MacOS и введем там соответствующие команды. Первым делом перейдем в каталог, где лежит наш файл с программой с помощью команды:
В данном случае файл находится в каталоге C:\Java.

Затем cкомпилируем программу с помощью команды
Обратите внимание, что весь путь к компилятору javac берется в кавычки, а затем через пробел идет название нашего файла, который содержит класс программы.
После этого программа компилируется в байт-код, и в каталоге C:\Java можно будет найти новый файл Program.class . Это и будет файл с байт-кодом программы. Теперь нам надо его запустить с помощью утилиты java:
Здесь уже расширение у файла не надо использовать.
Для ОС Windows весь процесс будет выглядеть следующим образом:

Добавление java в переменную Path
Для компиляции приходится вводить полный путь к комилятору javac, что может быть сопряжено с ошибками при вводе, да и каждый раз вводить полный путь тоже неудобно. Чтобы в дальнейшем облегчить работу, добавим путь к JDK в переменную PATH в переменных среды. Если мы работаем в Windows, то для добавления переменной среды через поиск найдем найдем параметр Изменение системных переменных среды . Для этого введем в поле поиска «Изменение системных переменных среды»:

Выберем пункт Изменение системных переменных среды . И сначала нам откроется окно «Свойства системы», где нажмем на кнопку Переменные среды :

Затем нам откроется окно, где мы можем увидеть все переменные среды. (Также можно перейти через Параметры и пункт Система ->Дополнительные параметры системы ->Переменные среды )
Здесь нам нужно исправить системную переменную Path . Для этого выделим ее и нажмем на кнопку «Изменить»:

В эту переменную Path нам надо добавить путь к инструментам JDK. И тут есть два момента. Во-первых, при установке jdk по умолчанию ряд утилит также устанавливаются в папку C:\Program Files\Common Files\Oracle\Java\javapath . В том числе это такие файлы как java.exe и javac.exe. И путь к этой папке по умолчанию добавляется в перемнную Path. То есть мы можем использовать этот путь.
Второй момент — в последних сборках Windows компания Microsoft также устанавливает свои сборки JDK, точнее OpenJDK, которые также по умолчанию добавляются в переменную Path и которые мы также можем использовать. Но у этих сборок есть большой минус — они применяют одну из прошлых версий JDK (обычно это LTS-сборки). Например, в моем случае это 11-я версия, хотя текущей является 19-я.
Чтобы использовать последнюю 19-ю версию среди путей в переменной Path убедимся, что путь C:\Program Files\Common Files\Oracle\Java\javapath располагается выше путей к сборкам JDK от Microsoft. Для перемещения определенного пути вверх среди переменных среды можно использовать кнопку «Вверх:

Также можно напрямую создать использовать путь «C:\Program Files\Java\jdk-19\bin».

Для создания новой переменной надо нажать на кнопку «Создать» и ввести в новое поле путь «C:\Program Files\Java\jdk-19\bin». Но опять же его следуется с помощью кнопки Вверх поместить над путями к OpenJDK от Microsoft.
После установки переменной Path перейдем к командной строке/терминалу (в более старых версиях Windows может потребоваться перезауск командной строки) и для проверки версии введем команду
Консоль нам должна в ответ ввести номер только что установленной версии JDK:
The java Command
options Optional: Specifies command-line options separated by spaces. See Overview of Java Options for a description of available options. mainclass Specifies the name of the class to be launched. Command-line entries following classname are the arguments for the main method. -jar jarfile Executes a program encapsulated in a JAR file. The jarfile argument is the name of a JAR file with a manifest that contains a line in the form Main-Class: classname that defines the class with the public static void main(String[] args) method that serves as your application’s starting point. When you use -jar , the specified JAR file is the source of all user classes, and other class path settings are ignored. If you’re using JAR files, then see jar. -m or —module module[ / mainclass]
Executes the main class in a module specified by mainclass if it is given, or, if it is not given, the value in the module. In other words, mainclass can be used when it is not specified by the module, or to override the value when it is specified.
source-file Only used to launch a single source-file program. Specifies the source file that contains the main class when using source-file mode. See Using Source-File Mode to Launch Single-File Source-Code Programs args . Optional: Arguments following mainclass, source-file, -jar jarfile, and -m or —module module / mainclass are passed as arguments to the main class.
Description
The java command starts a Java application. It does this by starting the Java Virtual Machine (JVM), loading the specified class, and calling that class’s main() method. The method must be declared public and static , it must not return any value, and it must accept a String array as a parameter. The method declaration has the following form:
public static void main(String[] args)
In source-file mode, the java command can launch a class declared in a source file. See Using Source-File Mode to Launch Single-File Source-Code Programs for a description of using the source-file mode.
Note: You can use the JDK_JAVA_OPTIONS launcher environment variable to prepend its content to the actual command line of the java launcher. See Using the JDK_JAVA_OPTIONS Launcher Environment Variable.
By default, the first argument that isn’t an option of the java command is the fully qualified name of the class to be called. If -jar is specified, then its argument is the name of the JAR file containing class and resource files for the application. The startup class must be indicated by the Main-Class manifest header in its manifest file.
Arguments after the class file name or the JAR file name are passed to the main() method.
javaw
Windows: The javaw command is identical to java , except that with javaw there’s no associated console window. Use javaw when you don’t want a command prompt window to appear. The javaw launcher will, however, display a dialog box with error information if a launch fails.
Using Source-File Mode to Launch Single-File Source-Code Programs
To launch a class declared in a source file, run the java launcher in source-file mode. Entering source-file mode is determined by two items on the java command line:
The first item on the command line that is not an option or part of an option. In other words, the item in the command line that would otherwise be the main class name.
The —source version option, if present.
If the class identifies an existing file that has a .java extension, or if the —source option is specified, then source-file mode is selected. The source file is then compiled and run. The —source option can be used to specify the source version or N of the source code. This determines the API that can be used. When you set —source N, you can only use the public API that was defined in JDK N.
Note: The valid values of N change for each release, with new values added and old values removed. You’ll get an error message if you use a value of N that is no longer supported. Supported values of N for this release are 7 , 8 , 9 , 10 , 11 , 12 , and 13 .
If the file does not have the .java extension, the —source option must be used to tell the java command to use the source-file mode. The —source option is used for cases when the source file is a "script" to be executed and the name of the source file does not follow the normal naming conventions for Java source files.
In source-file mode, the effect is as though the source file is compiled into memory, and the first class found in the source file is executed. Any arguments placed after the name of the source file in the original command line are passed to the compiled class when it is executed.
For example, if a file were named HelloWorld.java and contained a class named hello.World , then the source-file mode command to launch the class would be:
The example illustrates that the class can be in a named package, and does not need to be in the unnamed package. This use of source-file mode is informally equivalent to using the following two commands where hello.World is the name of the class in the package:
In source-file mode, any additional command-line options are processed as follows:
The launcher scans the options specified before the source file for any that are relevant in order to compile the source file.
This includes: —class-path , —module-path , —add-exports , —add-modules , —limit-modules , —patch-module , —upgrade-module-path , and any variant forms of those options. It also includes the new —enable-preview option, described in JEP 12.
No provision is made to pass any additional options to the compiler, such as -processor or -Werror .
Command-line argument files ( @ -files) may be used in the standard way. Long lists of arguments for either the VM or the program being invoked may be placed in files specified on the command-line by prefixing the filename with an @ character.
In source-file mode, compilation proceeds as follows:
Any command-line options that are relevant to the compilation environment are taken into account.
No other source files are found and compiled, as if the source path is set to an empty value.
Annotation processing is disabled, as if -proc:none is in effect.
If a version is specified, via the —source option, the value is used as the argument for an implicit —release option for the compilation. This sets both the source version accepted by compiler and the system API that may be used by the code in the source file.
The source file is compiled in the context of an unnamed module.
The source file should contain one or more top-level classes, the first of which is taken as the class to be executed.
The compiler does not enforce the optional restriction defined at the end of JLS ??7.6, that a type in a named package should exist in a file whose name is composed from the type name followed by the .java extension.
If the source file contains errors, appropriate error messages are written to the standard error stream, and the launcher exits with a non-zero exit code.
In source-file mode, execution proceeds as follows:
The class to be executed is the first top-level class found in the source file. It must contain a declaration of the standard public static void main(String[]) method.
The compiled classes are loaded by a custom class loader, that delegates to the application class loader. This implies that classes appearing on the application class path cannot refer to any classes declared in the source file.
The compiled classes are executed in the context of an unnamed module, as though —add-modules=ALL-DEFAULT is in effect. This is in addition to any other —add-module options that may be have been specified on the command line.
Any arguments appearing after the name of the file on the command line are passed to the standard main method in the obvious way.
It is an error if there is a class on the application class path whose name is the same as that of the class to be executed.
Using the JDK_JAVA_OPTIONS Launcher Environment Variable
JDK_JAVA_OPTIONS prepends its content to the options parsed from the command line. The content of the JDK_JAVA_OPTIONS environment variable is a list of arguments separated by white-space characters (as determined by isspace() ). These are prepended to the command line arguments passed to java launcher. The encoding requirement for the environment variable is the same as the java command line on the system. JDK_JAVA_OPTIONS environment variable content is treated in the same manner as that specified in the command line.
Single ( ‘ ) or double ( " ) quotes can be used to enclose arguments that??contain whitespace characters. All content between the open quote and the first matching close quote are preserved by simply removing the pair of quotes. In case a matching quote is not found, the launcher will abort with an error message. @ -files are supported as they are specified in the command line. However, as in @ -files, use of a wildcard is not supported. In order to mitigate potential misuse of JDK_JAVA_OPTIONS behavior, options that specify the main class (such as -jar ) or cause the java launcher to exit without executing the main class (such as -h ) are disallowed in the environment variable. If any of these options appear in the environment variable, the launcher will abort with an error message. When JDK_JAVA_OPTIONS is set, the launcher prints a message to stderr as a reminder.
Example:
is equivalent to the command line:
Overview of Java Options
The java command supports a wide range of options in the following categories:
Standard Options for Java: Options guaranteed to be supported by all implementations of the Java Virtual Machine (JVM). They’re used for common actions, such as checking the version of the JRE, setting the class path, enabling verbose output, and so on.
Extra Options for Java: General purpose options that are specific to the Java HotSpot Virtual Machine. They aren’t guaranteed to be supported by all JVM implementations, and are subject to change. These options start with -X .
The advanced options aren’t recommended for casual use. These are developer options used for tuning specific areas of the Java HotSpot Virtual Machine operation that often have specific system requirements and may require privileged access to system configuration parameters. Several examples of performance tuning are provided in Performance Tuning Examples. These options aren’t guaranteed to be supported by all JVM implementations and are subject to change. Advanced options start with -XX .
Advanced Runtime Options for Java: Control the runtime behavior of the Java HotSpot VM.
Advanced JIT Compiler Options for java: Control the dynamic just-in-time (JIT) compilation performed by the Java HotSpot VM.
Advanced Serviceability Options for Java: Enable gathering system information and performing extensive debugging.
Advanced Garbage Collection Options for Java: Control how garbage collection (GC) is performed by the Java HotSpot
Boolean options are used to either enable a feature that’s disabled by default or disable a feature that’s enabled by default. Such options don’t require a parameter. Boolean -XX options are enabled using the plus sign ( -XX:+ OptionName) and disabled using the minus sign ( -XX:- OptionName).
For options that require an argument, the argument may be separated from the option name by a space, a colon (:), or an equal sign (=), or the argument may directly follow the option (the exact syntax differs for each option). If you’re expected to specify the size in bytes, then you can use no suffix, or use the suffix k or K for kilobytes (KB), m or M for megabytes (MB), or g or G for gigabytes (GB). For example, to set the size to 8 GB, you can specify either 8g , 8192m , 8388608k , or 8589934592 as the argument. If you are expected to specify the percentage, then use a number from 0 to 1. For example, specify 0.25 for 25%.
The following sections describe the options that are obsolete, deprecated, and removed:
Deprecated Java Options: Accepted and acted upon — a warning is issued when they’re used.
Obsolete Java Options: Accepted but ignored — a warning is issued when they’re used.
Removed Java Options: Removed — using them results in an error.
Standard Options for Java
These are the most commonly used options supported by all implementations of the JVM.
Note: To specify an argument for a long option, you can use either — name = value or — name value.
Loads the specified native agent library. After the library name, a comma-separated list of options specific to the library can be used.
Oracle Solaris, Linux, and macOS: If the option -agentlib:foo is specified, then the JVM attempts to load the library named libfoo.so in the location specified by the LD_LIBRARY_PATH system variable (on macOS this variable is DYLD_LIBRARY_PATH ).
Windows: If the option -agentlib:foo is specified, then the JVM attempts to load the library named foo.dll in the location specified by the PATH system variable.
The following example shows how to load the Java Debug Wire Protocol (JDWP) library and listen for the socket connection on port 8000, suspending the JVM before the main class loads:
A semicolon ( ; ) separated list of directories, JAR archives, and ZIP archives to search for class files.
Specifying classpath overrides any setting of the CLASSPATH environment variable. If the class path option isn’t used and classpath isn’t set, then the user class path consists of the current directory (.).
As a special convenience, a class path element that contains a base name of an asterisk (*) is considered equivalent to specifying a list of all the files in the directory with the extension .jar or .JAR . A Java program can’t tell the difference between the two invocations. For example, if the directory mydir contains a.jar and b.JAR , then the class path element mydir/* is expanded to A.jar:b.JAR , except that the order of JAR files is unspecified. All .jar files in the specified directory, even hidden ones, are included in the list. A class path entry consisting of an asterisk (*) expands to a list of all the jar files in the current directory. The CLASSPATH environment variable, where defined, is similarly expanded. Any class path wildcard expansion that occurs before the Java VM is started. Java programs never see wildcards that aren’t expanded except by querying the environment, such as by calling System.getenv("CLASSPATH") .
—disable-@files Can be used anywhere on the command line, including in an argument file, to prevent further @filename expansion. This option stops expanding @ -argfiles after the option. —enable-preview Allows classes to depend on preview features of the release. —module-path modulepath. or -p modulepath A semicolon ( ; ) separated list of directories in which each directory is a directory of modules. —upgrade-module-path modulepath. A semicolon ( ; ) separated list of directories in which each directory is a directory of modules that replace upgradeable modules in the runtime image. —add-modules module[ , module. ] Specifies the root modules to resolve in addition to the initial module. module also can be ALL-DEFAULT , ALL-SYSTEM , and ALL-MODULE-PATH . —list-modules Lists the observable modules and then exits. -d module_name or —describe-module module_name Describes a specified module and then exits. —dry-run Creates the VM but doesn’t execute the main method. This —dry-run option might be useful for validating the command-line options such as the module system configuration. —validate-modules Validates all modules and exit. This option is helpful for finding conflicts and other errors with modules on the module path. -D property = value Sets a system property value. The property variable is a string with no spaces that represents the name of the property. The value variable is a string that represents the value of the property. If value is a string with spaces, then enclose it in quotation marks (for example -Dfoo="foo bar" ). -disableassertions [ : [packagename]. | : classname] or -da [ : [packagename]. | : classname]
Disables assertions. By default, assertions are disabled in all packages and classes. With no arguments, -disableassertions ( -da ) disables assertions in all packages and classes. With the packagename argument ending in . , the switch disables assertions in the specified package and any subpackages. If the argument is simply . , then the switch disables assertions in the unnamed package in the current working directory. With the classname argument, the switch disables assertions in the specified class.
The -disableassertions ( -da ) option applies to all class loaders and to system classes (which don’t have a class loader). There’s one exception to this rule: If the option is provided with no arguments, then it doesn’t apply to system classes. This makes it easy to disable assertions in all classes except for system classes. The -disablesystemassertions option enables you to disable assertions in all system classes. To explicitly enable assertions in specific packages or classes, use the -enableassertions ( -ea ) option. Both options can be used at the same time. For example, to run the MyClass application with assertions enabled in the package com.wombat.fruitbat (and any subpackages) but disabled in the class com.wombat.fruitbat.Brickbat , use the following command:
java -ea:com.wombat.fruitbat. -da:com.wombat.fruitbat.Brickbat MyClass
Enables assertions. By default, assertions are disabled in all packages and classes. With no arguments, -enableassertions ( -ea ) enables assertions in all packages and classes. With the packagename argument ending in . , the switch enables assertions in the specified package and any subpackages. If the argument is simply . , then the switch enables assertions in the unnamed package in the current working directory. With the classname argument, the switch enables assertions in the specified class.
The -enableassertions ( -ea ) option applies to all class loaders and to system classes (which don’t have a class loader). There’s one exception to this rule: If the option is provided with no arguments, then it doesn’t apply to system classes. This makes it easy to enable assertions in all classes except for system classes. The -enablesystemassertions option provides a separate switch to enable assertions in all system classes. To explicitly disable assertions in specific packages or classes, use the -disableassertions ( -da ) option. If a single command contains multiple instances of these switches, then they’re processed in order, before loading any classes. For example, to run the MyClass application with assertions enabled only in the package com.wombat.fruitbat (and any subpackages) but disabled in the class com.wombat.fruitbat.Brickbat , use the following command:
java -ea:com.wombat.fruitbat. -da:com.wombat.fruitbat.Brickbat MyClass
Shows the splash screen with the image specified by imagepath. HiDPI scaled images are automatically supported and used if available. The unscaled image file name, such as image.ext , should always be passed as the argument to the -splash option. The most appropriate scaled image provided is picked up automatically.
For example, to show the splash.gif file from the images directory when starting your application, use the following option:
See the SplashScreen API documentation for more information.
-verbose:class Displays information about each loaded class. -verbose:gc Displays information about each garbage collection (GC) event. -verbose:jni Displays information about the use of native methods and other Java Native Interface (JNI) activity. -verbose:module Displays information about the modules in use. —version Prints product version to the output stream and exits. -version Prints product version to the error stream and exits. -X Prints the help on extra options to the error stream. —help-extra Prints the help on extra options to the output stream. @ argfile
Specifies one or more argument files prefixed by @ used by the java command. It isn’t uncommon for the java command line to be very long because of the .jar files needed in the classpath. The @ argfile option overcomes command-line length limitations by enabling the launcher to expand the contents of argument files after shell expansion, but before argument processing. Contents in the argument files are expanded because otherwise, they would be specified on the command line until the —disable-@files option was encountered.
The argument files can also contain the main class name and all options. If an argument file contains all of the options required by the java command, then the command line could simply be:
See java Command-Line Argument Files for a description and examples of using @ -argfiles.
Extra Options for Java
The following java options are general purpose options that are specific to the Java HotSpot Virtual Machine.
-Xbatch Disables background compilation. By default, the JVM compiles the method as a background task, running the method in interpreter mode until the background compilation is finished. The -Xbatch flag disables background compilation so that compilation of all methods proceeds as a foreground task until completed. This option is equivalent to -XX:-BackgroundCompilation . -Xbootclasspath/a: directories|zip|JAR-files
Specifies a list of directories, JAR files, and ZIP archives to append to the end of the default bootstrap class path.
Oracle Solaris, Linux, and macOS: Colons ( : ) separate entities in this list.
Windows: Semicolons ( ; ) separate entities in this list.
-Xcheck:jni Performs additional checks for Java Native Interface (JNI) functions. Specifically, it validates the parameters passed to the JNI function and the runtime environment data before processing the JNI request. It also checks for pending exceptions between JNI calls. Any invalid data encountered indicates a problem in the native code, and the JVM terminates with an irrecoverable error in such cases. Expect a performance degradation when this option is used. -Xcomp Forces compilation of methods on first invocation. By default, the Client VM ( -client ) performs 1,000 interpreted method invocations and the Server VM ( -server ) performs 10,000 interpreted method invocations to gather information for efficient compilation. Specifying the -Xcomp option disables interpreted method invocations to increase compilation performance at the expense of efficiency. You can also change the number of interpreted method invocations before compilation using the -XX:CompileThreshold option. -Xdebug Does nothing. Provided for backward compatibility. -Xdiag Shows additional diagnostic messages. -Xint Runs the application in interpreted-only mode. Compilation to native code is disabled, and all bytecode is executed by the interpreter. The performance benefits offered by the just-in-time (JIT) compiler aren’t present in this mode. -Xinternalversion Displays more detailed JVM version information than the -version option, and then exits. -Xlog: option Configure or enable logging with the Java Virtual Machine (JVM) unified logging framework. See Enable Logging with the JVM Unified Logging Framework. -Xmixed Executes all bytecode by the interpreter except for hot methods, which are compiled to native code. -Xmn size
Sets the initial and maximum size (in bytes) of the heap for the young generation (nursery) in the generational collectors. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, or g or G to indicate gigabytes. The young generation region of the heap is used for new objects. GC is performed in this region more often than in other regions. If the size for the young generation is too small, then a lot of minor garbage collections are performed. If the size is too large, then only full garbage collections are performed, which can take a long time to complete. It is recommended that you do not set the size for the young generation for the G1 collector, and keep the size for the young generation greater than 25% and less than 50% of the overall heap size for other collectors. The following examples show how to set the initial and maximum size of young generation to 256 MB using various units:
Instead of the -Xmn option to set both the initial and maximum size of the heap for the young generation, you can use -XX:NewSize to set the initial size and -XX:MaxNewSize to set the maximum size.
Sets the minimum and initial size (in bytes) of the heap. This value must be a multiple of 1024 and greater than 1 MB. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes. The following examples show how to set the size of allocated memory to 6 MB using various units:
Instead of the -Xms option to set both the minimum and initial size of the heap, you can use -XX:MinHeapSize to set the minimum size and -XX:InitialHeapSize to set the initial size.
If you don’t set this option, the initial size is set as the sum of the sizes allocated for the old generation and the young generation. The initial size of the heap for the young generation can be set using the -Xmn option or the -XX:NewSize option.
Specifies the maximum size (in bytes) of the heap. This value must be a multiple of 1024 and greater than 2 MB. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, or g or G to indicate gigabytes. The default value is chosen at runtime based on system configuration. For server deployments, -Xms and -Xmx are often set to the same value. The following examples show how to set the maximum allowed size of allocated memory to 80 MB using various units:
The -Xmx option is equivalent to -XX:MaxHeapSize .
-Xnoclassgc Disables garbage collection (GC) of classes. This can save some GC time, which shortens interruptions during the application run. When you specify -Xnoclassgc at startup, the class objects in the application are left untouched during GC and are always be considered live. This can result in more memory being permanently occupied which, if not used carefully, throws an out-of-memory exception. -Xrs
Reduces the use of operating system signals by the JVM. Shutdown hooks enable the orderly shutdown of a Java application by running user cleanup code (such as closing database connections) at shutdown, even if the JVM terminates abruptly.
Oracle Solaris, Linux, and macOS:
The JVM catches signals to implement shutdown hooks for unexpected termination. The JVM uses SIGHUP , SIGINT , and SIGTERM to initiate the running of shutdown hooks.
Applications embedding the JVM frequently need to trap signals such as SIGINT or SIGTERM , which can lead to interference with the JVM signal handlers. The -Xrs option is available to address this issue. When -Xrs is used, the signal masks for SIGINT , SIGTERM , SIGHUP , and SIGQUIT aren’t changed by the JVM, and signal handlers for these signals aren’t installed.
Windows:
The JVM watches for console control events to implement shutdown hooks for unexpected termination. Specifically, the JVM registers a console control handler that begins shutdown-hook processing and returns TRUE for CTRL_C_EVENT , CTRL_CLOSE_EVENT , CTRL_LOGOFF_EVENT , and CTRL_SHUTDOWN_EVENT .
The JVM uses a similar mechanism to implement the feature of dumping thread stacks for debugging purposes. The JVM uses CTRL_BREAK_EVENT to perform thread dumps.
If the JVM is run as a service (for example, as a servlet engine for a web server), then it can receive CTRL_LOGOFF_EVENT but shouldn’t initiate shutdown because the operating system doesn’t actually terminate the process. To avoid possible interference such as this, the -Xrs option can be used. When the -Xrs option is used, the JVM doesn’t install a console control handler, implying that it doesn’t watch for or process CTRL_C_EVENT , CTRL_CLOSE_EVENT , CTRL_LOGOFF_EVENT , or CTRL_SHUTDOWN_EVENT .
There are two consequences of specifying -Xrs :
Oracle Solaris, Linux, and macOS: SIGQUIT thread dumps aren’t available.
Windows: Ctrl + Break thread dumps aren’t available.
User code is responsible for causing shutdown hooks to run, for example, by calling the System.exit() when the JVM is to be terminated.
Sets the class data sharing (CDS) mode.
Possible mode arguments for this option include the following:
auto Use shared class data if possible (default). on Require using shared class data, otherwise fail.
Note: The -Xshare:on option is used for testing purposes only and may cause intermittent failures due to the use of address space layout randomization by the operation system. This option should not be used in production environments.
Shows settings and continues. Possible category arguments for this option include the following:
all Shows all categories of settings. This is the default value. locale Shows settings related to locale. properties Shows settings related to system properties. vm Shows the settings of the JVM. system Linux: Shows host system or container configuration and continues. -Xss size
Sets the thread stack size (in bytes). Append the letter k or K to indicate KB, m or M to indicate MB, or g or G to indicate GB. The default value depends on the platform:
Linux/x64 (64-bit): 1024 KB
macOS (64-bit): 1024 KB
Oracle Solaris (64-bit): 1024 KB
Windows: The default value depends on virtual memory
The following examples set the thread stack size to 1024 KB in different units:
This option is similar to -XX:ThreadStackSize .
—add-reads module = target-module( , target-module)* Updates module to read the target-module, regardless of the module declaration. target-module can be all unnamed to read all unnamed modules. —add-exports module / package = target-module( , target-module)* Updates module to export package to target-module, regardless of module declaration. The target-module can be all unnamed to export to all unnamed modules. —add-opens module / package = target-module( , target-module)* Updates module to open package to target-module, regardless of module declaration. —illegal-access= parameter
When present at run time, —illegal-access= takes a keyword parameter to specify a mode of operation:
Note: This option will be removed in a future release.
permit : This mode opens each package in each module in the run-time image to code in all unnamed modules ( such as code on the class path), if that package existed in JDK 8. This enables both static access, (for example, by compiled bytecode, and deep reflective access) through the platform’s various reflection APIs. The first reflective-access operation to any such package causes a warning to be issued. However, no warnings are issued after the first occurrence. This single warning describes how to enable further warnings. This mode is the default for the current JDK but will change in a future release.
warn : This mode is identical to permit except that a warning message is issued for each illegal reflective-access operation.
debug : This mode is identical to warn except that both a warning message and a stack trace are issued for each illegal reflective-access operation.
deny : This mode disables all illegal-access operations except for those enabled by other command-line options, such as —add-opens . This mode will become the default in a future release.
The default mode, —illegal-access=permit , is intended to make you aware of code on the class path that reflectively accesses any JDK-internal APIs at least once. To learn about all such accesses, you can use the warn or the debug modes. For each library or framework on the class path that requires illegal access, you have two options:
If the component’s maintainers have already released a fixed version that no longer uses JDK-internal APIs then you can consider upgrading to that version.
If the component still needs to be fixed, then you can contact its maintainers and ask them to replace their use of JDK-internal APIs with the proper exported APIs.
If you must continue to use a component that requires illegal access, then you can eliminate the warning messages by using one or more —add-opens options to open only those internal packages to which access is required.
To verify that your application is ready for a future version of the JDK, run it with —illegal-access=deny along with any necessary —add-opens options. Any remaining illegal-access errors will most likely be due to static references from compiled code to JDK-internal APIs. You can identify those by running the jdeps tool with the —jdk-internals option. For performance reasons, the current JDK does not issue warnings for illegal static-access operations.
—limit-modules module[ , module. ] Specifies the limit of the universe of observable modules. —patch-module module = file( ; file)* Overrides or augments a module with classes and resources in JAR files or directories. —source version Sets the version of the source in source-file mode.
Extra Options for macOS
The following extra options are macOS specific.
-XstartOnFirstThread Runs the main() method on the first (AppKit) thread. -Xdock:name= application_name Overrides the default application name displayed in dock. -Xdock:icon= path_to_icon_file Overrides the default icon displayed in dock.
Advanced Options for Java
These java options can be used to enable other advanced options.
Unlocks the options intended for diagnosing the JVM. By default, this option is disabled and diagnostic options aren’t available.
Command line options that are enabled with the use of this option are not supported. If you encounter issues while using any of these options, it is very likely that you will be required to reproduce the problem without using any of these unsupported options before Oracle Support can assist with an investigation. It is also possible that any of these options may be removed or their behavior changed without any warning.
-XX:+UnlockExperimentalVMOptions Unlocks the options that provide experimental features in the JVM. By default, this option is disabled and experimental features aren’t available.
Advanced Runtime Options for Java
These java options control the runtime behavior of the Java HotSpot VM.
Overrides the number of CPUs that the VM will use to calculate the size of thread pools it will use for various operations such as Garbage Collection and ForkJoinPool.
The VM normally determines the number of available processors from the operating system. This flag can be useful for partitioning CPU resources when running multiple Java processes in docker containers. This flag is honored even if UseContainerSupport is not enabled. See -XX:-UseContainerSupport for a description of enabling and disabling container support.
Takes a path to the file system and uses memory mapping to allocate the object heap on the memory device. Using this option enables the HotSpot VM to allocate the Java object heap on an alternative memory device, such as an NV-DIMM, specified by the user.
Alternative memory devices that have the same semantics as DRAM, including the semantics of atomic operations, can be used instead of DRAM for the object heap without changing the existing application code. All other memory structures (such as the code heap, metaspace, and thread stacks) continue to reside in DRAM.
Some operating systems expose non-DRAM memory through the file system. Memory-mapped files in these file systems bypass the page cache and provide a direct mapping of virtual memory to the physical memory on the device. The existing heap related flags (such as -Xmx and -Xms ) and garbage-collection related flags continue to work as before.
Disables the Compact Strings feature. By default, this option is enabled. When this option is enabled, Java Strings containing only single-byte characters are internally represented and stored as single-byte-per-character Strings using ISO-8859-1 / Latin-1 encoding. This reduces, by 50%, the amount of space required for Strings containing only single-byte characters. For Java Strings containing at least one multibyte character: these are represented and stored as 2 bytes per character using UTF-16 encoding. Disabling the Compact Strings feature forces the use of UTF-16 encoding as the internal representation for all Java Strings.
Cases where it may be beneficial to disable Compact Strings include the following:
When it’s known that an application overwhelmingly will be allocating multibyte character Strings
In the unexpected event where a performance regression is observed in migrating from Java SE 8 to Java SE 9 and an analysis shows that Compact Strings introduces the regression
In both of these scenarios, disabling Compact Strings makes sense.
Specifies the path and file name to which error data is written when an irrecoverable error occurs. By default, this file is created in the current working directory and named hs_err_pid pid .log where pid is the identifier of the process that encountered the error.
The following example shows how to set the default log file (note that the identifier of the process is specified as %p ):
Oracle Solaris, Linux, and macOS: The following example shows how to set the error log to /var/log/java/java_error.log :
Windows: The following example shows how to set the error log file to C:/log/java/java_error.log :
If the file exists, and is writeable, then it will be overwritten. Otherwise, if the file can’t be created in the specified directory (due to insufficient space, permission problem, or another issue), then the file is created in the temporary directory for the operating system:
Oracle Solaris, Linux, and macOS: The temporary directory is /tmp .
Windows: The temporary directory is specified by the value of the TMP environment variable; if that environment variable isn’t defined, then the value of the TEMP environment variable is used.
Sets the parameters that control the behavior of JFR.
The following list contains the available JFR parameter = value entries:
globalbuffersize= size Specifies the total amount of primary memory used for data retention. The default value is based on the value specified for memorysize . Change the memorysize parameter to alter the size of global buffers. maxchunksize= size Specifies the maximum size (in bytes) of the data chunks in a recording. Append m or M to specify the size in megabytes (MB), or g or G to specify the size in gigabytes (GB). By default, the maximum size of data chunks is set to 12 MB. The minimum allowed is 1 MB. memorysize= size Determines how much buffer memory should be used, and sets the globalbuffersize and numglobalbuffers parameters based on the size specified. Append m or M to specify the size in megabytes (MB), or g or G to specify the size in gigabytes (GB). By default, the memory size is set to 10 MB. numglobalbuffers Specifies the number of global buffers used. The default value is based on the memory size specified. Change the memorysize parameter to alter the number of global buffers. old-object-queue-size=number-of-objects Maximum number of old objects to track. By default, the number of objects is set to 256. repository= path Specifies the repository (a directory) for temporary disk storage. By default, the system’s temporary directory is used. retransform= < true | false >Specifies whether event classes should be retransformed using JVMTI. If false, instrumentation is added when event classes are loaded. By default, this parameter is enabled. samplethreads= < true | false >Specifies whether thread sampling is enabled. Thread sampling occurs only if the sampling event is enabled along with this parameter. By default, this parameter is enabled. stackdepth= depth Stack depth for stack traces. By default, the depth is set to 64 method calls. The maximum is 2048. Values greater than 64 could create significant overhead and reduce performance. threadbuffersize= size Specifies the per-thread local buffer size (in bytes). By default, the local buffer size is set to 8 kilobytes, with a minimum value of 4 kilobytes. Overriding this parameter could reduce performance and is not recommended.
You can specify values for multiple parameters by separating them with a comma.
Sets the maximum size (in bytes) for large pages used for the Java heap. The size argument must be a power of 2 (2, 4, 8, 16, and so on). Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, or g or G to indicate gigabytes. By default, the size is set to 0, meaning that the JVM chooses the size for large pages automatically. See Large Pages.
The following example describes how to set the large page size to 4 megabytes (MB):
Sets the maximum total size (in bytes) of the java.nio package, direct-buffer allocations. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, or g or G to indicate gigabytes. By default, the size is set to 0, meaning that the JVM chooses the size for NIO direct-buffer allocations automatically.
The following examples illustrate how to set the NIO size to 1024 KB in different units:
-XX:-MaxFDLimit Disables the attempt to set the soft limit for the number of open file descriptors to the hard limit. By default, this option is enabled on all platforms, but is ignored on Windows. The only time that you may need to disable this is on Mac OS, where its use imposes a maximum of 10240, which is lower than the actual system maximum. -XX:NativeMemoryTracking= mode
Specifies the mode for tracking JVM native memory usage. Possible mode arguments for this option include the following:
off Instructs not to track JVM native memory usage. This is the default behavior if you don’t specify the -XX:NativeMemoryTracking option. summary Tracks memory usage only by JVM subsystems, such as Java heap, class, code, and thread. detail In addition to tracking memory usage by JVM subsystems, track memory usage by individual CallSite , individual virtual memory region and its committed regions. -XX:ObjectAlignmentInBytes= alignment
Sets the memory alignment of Java objects (in bytes). By default, the value is set to 8 bytes. The specified value should be a power of 2, and must be within the range of 8 and 256 (inclusive). This option makes it possible to use compressed pointers with large Java heap sizes.
The heap size limit in bytes is calculated as:
Note: As the alignment value increases, the unused space between objects also increases. As a result, you may not realize any benefits from using compressed pointers with large Java heap sizes.
Sets a custom command or a series of semicolon-separated commands to run when an irrecoverable error occurs. If the string contains spaces, then it must be enclosed in quotation marks.
Oracle Solaris, Linux, and macOS: The following example shows how the -XX:OnError option can be used to run the gcore command to create a core image, and start the gdb debugger to attach to the process in case of an irrecoverable error (the %p designates the current process identifier):
Windows: The following example shows how the -XX:OnError option can be used to run the userdump.exe utility to obtain a crash dump in case of an irrecoverable error (the %p designates the current process identifier). This example assumes that the path to the userdump.exe utility is specified in the PATH environment variable:
Specifies the path and name of the class data sharing (CDS) archive file
-XX:SharedArchiveConfigFile =shared_config_file Specifies additional shared data added to the archive file. -XX:SharedClassListFile= file_name
Specifies the text file that contains the names of the classes to store in the class data sharing (CDS) archive. This file contains the full name of one class per line, except slashes ( / ) replace dots ( . ). For example, to specify the classes java.lang.Object and hello.Main , create a text file that contains the following two lines:
The classes that you specify in this text file should include the classes that are commonly used by the application. They may include any classes from the application, extension, or bootstrap class paths.
-XX:+ShowMessageBoxOnError Enables the display of a dialog box when the JVM experiences an irrecoverable error. This prevents the JVM from exiting and keeps the process active so that you can attach a debugger to it to investigate the cause of the error. By default, this option is disabled. -XX:StartFlightRecording= parameter = value
Starts a JFR recording for the Java application. This option is equivalent to the JFR.start diagnostic command that starts a recording during runtime. You can set the following parameter = value entries when starting a JFR recording:
delay= time Specifies the delay between the Java application launch time and the start of the recording. Append s to specify the time in seconds, m for minutes, h for hours, or d for days (for example, specifying 10m means 10 minutes). By default, there’s no delay, and this parameter is set to 0. disk= < true | false >Specifies whether to write data to disk while recording. By default, this parameter is enabled. dumponexit= < true | false >Specifies if the running recording is dumped when the JVM shuts down. If enabled and a filename is not entered, the recording is written to a file in the directory where the process was started. The file name is a system-generated name that contains the process ID, recording ID, and current timestamp, similar to hotspot-pid-47496-id-1-2018_01_25_19_10_41.jfr . By default, this parameter is disabled. duration= time Specifies the duration of the recording. Append s to specify the time in seconds, m for minutes, h for hours, or d for days (for example, specifying 5h means 5 hours). By default, the duration isn’t limited, and this parameter is set to 0. filename= path
Specifies the path and name of the file to which the recording is written when the recording is stopped, for example:
- recording.jfr
- /home/user/recordings/recording.jfr
- c:\recordings\recording.jfr
Specifies whether to collect the path to garbage collection (GC) roots at the end of a recording. By default, this parameter is disabled.
The path to GC roots is useful for finding memory leaks, but collecting it is time-consuming. Enable this option only when you start a recording for an application that you suspect has a memory leak. If the settings parameter is set to profile , the stack trace from where the potential leaking object was allocated is included in the information collected.
Specifies the path and name of the event settings file (of type JFC). By default, the default.jfc file is used, which is located in JRE_HOME/lib/jfr . This default settings file collects a predefined set of information with low overhead, so it has minimal impact on performance and can be used with recordings that run continuously.
A second settings file is also provided, profile.jfc, which provides more data than the default configuration, but can have more overhead and impact performance. Use this configuration for short periods of time when more information is needed.
You can specify values for multiple parameters by separating them with a comma.
Sets the Java thread stack size (in kilobytes). Use of a scaling suffix, such as k , results in the scaling of the kilobytes value so that -XX:ThreadStackSize=1k sets the Java thread stack size??to 1024*1024 bytes or 1 megabyte. The default value depends on the platform:
Linux/x64 (64-bit): 1024 KB
macOS (64-bit): 1024 KB
Oracle Solaris (64-bit): 1024 KB
Windows: The default value depends on virtual memory
The following examples show how to set the thread stack size to 1 megabyte in different units:
This option is similar to -Xss .
Disables the use of biased locking. Some applications with significant amounts of uncontended synchronization may attain significant speedups with this flag enabled, but applications with certain patterns of locking may see slowdowns. .
By default, this option is enabled.
Disables the use of compressed pointers. By default, this option is enabled, and compressed pointers are used. This will automatically limit the maximum ergonomically determined Java heap size to the maximum amount of memory that can be covered by compressed pointers. By default this range is 32 GB.
With compressed oops enabled, object references are represented as 32-bit offsets instead of 64-bit pointers, which typically increases performance when running the application with Java heap sizes smaller than the compressed oops pointer range. This option works only for 64-bit JVMs.
It’s possible to use compressed pointers with Java heap sizes greater than 32 GB. See the -XX:ObjectAlignmentInBytes option.
The VM now provides automatic container detection support, which allows the VM to determine the amount of memory and number of processors that are available to a Java process running in docker containers. It uses this information to allocate system resources. This support is only available on Linux x64 platforms. ??If supported, the default for this flag is?? true , and container support is enabled by default. ??It??can be disabled with?? -XX:-UseContainerSupport .
Unified Logging is available to help to diagnose issues related to this support.
Use -Xlog:os+container=trace for maximum logging of container information. See Enable Logging with the JVM Unified Logging Framework for a description of using Unified Logging.
Linux only: This option is the equivalent of specifying -XX:+UseLargePages . This option is disabled by default. This option pre-allocates all large pages up-front, when memory is reserved; consequently the JVM can’t dynamically grow or shrink large pages memory areas; see -XX:UseTransparentHugePages if you want this behavior.
Enables the use of large page memory. By default, this option is disabled and large page memory isn’t used.
-XX:+UseTransparentHugePages Linux only: Enables the use of large pages that can dynamically grow or shrink. This option is disabled by default. You may encounter performance problems with transparent huge pages as the OS moves other pages around to create huge pages; this option is made available for experimentation. -XX:+AllowUserSignalHandlers Enables installation of signal handlers by the application. By default, this option is disabled and the application isn’t allowed to install signal handlers. -XX:VMOptionsFile= filename Allows user to specify VM options in a file, for example, java -XX:VMOptionsFile=/var/my_vm_options HelloWorld .
Advanced JIT Compiler Options for java
These java options control the dynamic just-in-time (JIT) compilation performed by the Java HotSpot VM.
Sets the number of lines to prefetch ahead of the instance allocation pointer. By default, the number of lines to prefetch is set to 1:
Only the Java HotSpot Server VM supports this option.
Sets the size (in bytes) of the prefetch distance for object allocation. Memory about to be written with the value of new objects is prefetched up to this distance starting from the address of the last allocated object. Each Java thread has its own allocation point.
Negative values denote that prefetch distance is chosen based on the platform. Positive values are bytes to prefetch. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, or g or G to indicate gigabytes. The default value is set to -1.
The following example shows how to set the prefetch distance to 1024 bytes:
Only the Java HotSpot Server VM supports this option.
Sets the prefetch instruction to prefetch ahead of the allocation pointer. Only the Java HotSpot Server VM supports this option. Possible values are from 0 to 3. The actual instructions behind the values depend on the platform. By default, the prefetch instruction is set to 0:
Only the Java HotSpot Server VM supports this option.
Sets the number of cache lines to load after the last object allocation by using the prefetch instructions generated in compiled code. The default value is 1 if the last allocated object was an instance, and 3 if it was an array.
The following example shows how to set the number of loaded cache lines to 5:
Only the Java HotSpot Server VM supports this option.
Sets the step size (in bytes) for sequential prefetch instructions. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, g or G to indicate gigabytes. By default, the step size is set to 16 bytes:
Only the Java HotSpot Server VM supports this option.
Sets the generated code style for prefetch instructions. The style argument is an integer from 0 to 3:
0 Don’t generate prefetch instructions. 1 Execute prefetch instructions after each allocation. This is the default parameter. 2 Use the thread-local allocation block (TLAB) watermark pointer to determine when prefetch instructions are executed. 3 Use BIS instruction on SPARC for allocation prefetch.
Only the Java HotSpot Server VM supports this option.
-XX:+BackgroundCompilation Enables background compilation. This option is enabled by default. To disable background compilation, specify -XX:-BackgroundCompilation (this is equivalent to specifying -Xbatch ). -XX:CICompilerCount= threads
Sets the number of compiler threads to use for compilation. By default, the number of threads is set to 2 for the server JVM, to 1 for the client JVM, and it scales to the number of cores if tiered compilation is used. The following example shows how to set the number of threads to 2:
Specifies a command to perform on a method. For example, to exclude the indexOf() method of the String class from being compiled, use the following:
Note that the full class name is specified, including all packages and subpackages separated by a slash ( / ). For easier cut-and-paste operations, it’s also possible to use the method name format produced by the -XX:+PrintCompilation and -XX:+LogCompilation options:
If the method is specified without the signature, then the command is applied to all methods with the specified name. However, you can also specify the signature of the method in the class file format. In this case, you should enclose the arguments in quotation marks, because otherwise the shell treats the semicolon as a command end. For example, if you want to exclude only the indexOf(String) method of the String class from being compiled, use the following:
You can also use the asterisk (*) as a wildcard for class and method names. For example, to exclude all indexOf() methods in all classes from being compiled, use the following:
The commas and periods are aliases for spaces, making it easier to pass compiler commands through a shell. You can pass arguments to -XX:CompileCommand using spaces as separators by enclosing the argument in quotation marks:
Note that after parsing the commands passed on the command line using the -XX:CompileCommand options, the JIT compiler then reads commands from the .hotspot_compiler file. You can add commands to this file or specify a different file using the -XX:CompileCommandFile option.
To add several commands, either specify the -XX:CompileCommand option multiple times, or separate each argument with the new line separator ( \n ). The following commands are available:
break Sets a breakpoint when debugging the JVM to stop at the beginning of compilation of the specified method. compileonly Excludes all methods from compilation except for the specified method. As an alternative, you can use the -XX:CompileOnly option, which lets you specify several methods. dontinline Prevents inlining of the specified method. exclude Excludes the specified method from compilation. help Prints a help message for the -XX:CompileCommand option. inline Attempts to inline the specified method. log Excludes compilation logging (with the -XX:+LogCompilation option) for all methods except for the specified method. By default, logging is performed for all compiled methods. option
Passes a JIT compilation option to the specified method in place of the last argument ( option ). The compilation option is set at the end, after the method name. For example, to enable the BlockLayoutByFrequency option for the append() method of the StringBuffer class, use the following:
You can specify multiple compilation options, separated by commas or spaces.
print Prints generated assembler code after compilation of the specified method. quiet
Instructs not to print the compile commands. By default, the commands that you specify with the -XX:CompileCommand option are printed; for example, if you exclude from compilation the indexOf() method of the String class, then the following is printed to standard output:
CompilerOracle: exclude java/lang/String.indexOf
You can suppress this by specifying the -XX:CompileCommand=quiet option before other -XX:CompileCommand options.
Sets the file from which JIT compiler commands are read. By default, the .hotspot_compiler file is used to store commands performed by the JIT compiler.
Each line in the command file represents a command, a class name, and a method name for which the command is used. For example, this line prints assembly code for the toString() method of the String class:
If you’re using commands for the JIT compiler to perform on methods, then see the -XX:CompileCommand option.
Adds directives from a file to the directives stack when a program starts. See Compiler Control.
The -XX:CompilerDirectivesFile option has to be used together with the -XX:UnlockDiagnosticVMOptions option that unlocks diagnostic JVM options.
Prints the directives stack when the program starts or when a new directive is added.
The -XX:+CompilerDirectivesPrint option has to be used together with the -XX:UnlockDiagnosticVMOptions option that unlocks diagnostic JVM options.
Sets the list of methods (separated by commas) to which compilation should be restricted. Only the specified methods are compiled. Specify each method with the full class name (including the packages and subpackages). For example, to compile only the length() method of the String class and the size() method of the List class, use the following:
Note that the full class name is specified, including all packages and subpackages separated by a slash ( / ). For easier cut and paste operations, it’s also possible to use the method name format produced by the -XX:+PrintCompilation and -XX:+LogCompilation options:
Although wildcards aren’t supported, you can specify only the class or package name to compile all methods in that class or package, as well as specify just the method to compile methods with this name in any class:
Sets the number of interpreted method invocations before compilation. By default, in the server JVM, the JIT compiler performs 10,000 interpreted method invocations to gather information for efficient compilation. For the client JVM, the default setting is 1,500 invocations. This option is ignored when tiered compilation is enabled; see the option -XX:-TieredCompilation . The following example shows how to set the number of interpreted method invocations to 5,000:
You can completely disable interpretation of Java methods before compilation by specifying the -Xcomp option.
-XX:CompileThresholdScaling= scale Provides unified control of first compilation. This option controls when methods are first compiled for both the tiered and the nontiered modes of operation. The CompileThresholdScaling option has an integer value between 0 and +Inf and scales the thresholds corresponding to the current mode of operation (both tiered and nontiered). Setting CompileThresholdScaling to a value less than 1.0 results in earlier compilation while values greater than 1.0 delay compilation. Setting CompileThresholdScaling to 0 is equivalent to disabling compilation. -XX:+DoEscapeAnalysis Enables the use of escape analysis. This option is enabled by default. To disable the use of escape analysis, specify -XX:-DoEscapeAnalysis . Only the Java HotSpot Server VM supports this option. -XX:InitialCodeCacheSize= size
Sets the initial code cache size (in bytes). Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, or g or G to indicate gigabytes. The default value is set to 500 KB. The initial code cache size shouldn’t be less than the system’s minimal memory page size. The following example shows how to set the initial code cache size to 32 KB:
Sets the maximum code size (in bytes) for compiled methods that should be inlined. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, or g or G to indicate gigabytes. Only compiled methods with the size smaller than the specified size is inlined. By default, the maximum code size is set to 1000 bytes:
Enables logging of compilation activity to a file named hotspot.log in the current working directory. You can specify a different log file path and name using the -XX:LogFile option.
By default, this option is disabled and compilation activity isn’t logged. The -XX:+LogCompilation option has to be used together with the -XX:UnlockDiagnosticVMOptions option that unlocks diagnostic JVM options.
You can enable verbose diagnostic output with a message printed to the console every time a method is compiled by using the -XX:+PrintCompilation option.
Sets the maximum bytecode size (in bytes) of a method to be inlined. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, or g or G to indicate gigabytes. By default, the maximum bytecode size is set to 35 bytes:
Sets the maximum number of nodes to be used during single method compilation. By default, the maximum number of nodes is set to 65,000:
Sets the size in bytes of the code segment containing nonmethod code.
A nonmethod code segment containing nonmethod code, such as compiler buffers and the bytecode interpreter. This code type stays in the code cache forever. This flag is used only if -XX:SegmentedCodeCache is enabled.
-XX:NonProfiledCodeHeapSize= size Sets the size in bytes of the code segment containing nonprofiled methods. This flag is used only if -XX:SegmentedCodeCache is enabled. -XX:MaxTrivialSize= size
Sets the maximum bytecode size (in bytes) of a trivial method to be inlined. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, or g or G to indicate gigabytes. By default, the maximum bytecode size of a trivial method is set to 6 bytes:
Enables printing of assembly code for bytecoded and native methods by using the external hsdis-<arch>.so or .dll library. For 64-bit VM on Windows, it’s hsdis-amd64.dll . This lets you to see the generated code, which may help you to diagnose performance issues.
By default, this option is disabled and assembly code isn’t printed. The -XX:+PrintAssembly option has to be used together with the -XX:UnlockDiagnosticVMOptions option that unlocks diagnostic JVM options.
-XX:ProfiledCodeHeapSize= size Sets the size in bytes of the code segment containing profiled methods. This flag is used only if -XX:SegmentedCodeCache is enabled. -XX:+PrintCompilation
Enables verbose diagnostic output from the JVM by printing a message to the console every time a method is compiled. This lets you to see which methods actually get compiled. By default, this option is disabled and diagnostic output isn’t printed.
You can also log compilation activity to a file by using the -XX:+LogCompilation option.
Enables printing of inlining decisions. This let’s you see which methods are getting inlined.
By default, this option is disabled and inlining information isn’t printed. The -XX:+PrintInlining option has to be used together with the -XX:+UnlockDiagnosticVMOptions option that unlocks diagnostic JVM options.
-XX:ReservedCodeCacheSize= size Sets the maximum code cache size (in bytes) for JIT-compiled code. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, or g or G to indicate gigabytes. The default maximum code cache size is 240 MB; if you disable tiered compilation with the option -XX:-TieredCompilation , then the default size is 48 MB. This option has a limit of 2 GB; otherwise, an error is generated. The maximum code cache size shouldn’t be less than the initial code cache size; see the option -XX:InitialCodeCacheSize . -XX:RTMAbortRatio= abort_ratio Specifies the RTM abort ratio is specified as a percentage (%) of all executed RTM transactions. If a number of aborted transactions becomes greater than this ratio, then the compiled code is deoptimized. This ratio is used when the -XX:+UseRTMDeopt option is enabled. The default value of this option is 50. This means that the compiled code is deoptimized if 50% of all transactions are aborted. -XX:RTMRetryCount= number_of_retries Specifies the number of times that the RTM locking code is retried, when it is aborted or busy, before falling back to the normal locking mechanism. The default value for this option is 5. The -XX:UseRTMLocking option must be enabled. -XX:+SegmentedCodeCache Enables segmentation of the code cache. Without the -XX:+SegmentedCodeCache , the code cache consists of one large segment. With -XX:+SegmentedCodeCache , we have separate segments for nonmethod, profiled method, and nonprofiled method code. These segments aren’t resized at runtime. The feature is enabled by default if tiered compilation is enabled ( -XX:+TieredCompilation ) and -XX:ReservedCodeCacheSize >= 240 MB. The advantages are better control of the memory footprint, reduced code fragmentation, and better iTLB/iCache behavior due to improved locality. iTLB/iCache is a CPU-specific term meaning Instruction Translation Lookaside Buffer (ITLB). ICache is an instruction cache in theCPU. The implementation of the code cache can be found in the file: /share/vm/code/codeCache.cpp . -XX:StartAggressiveSweepingAt= percent Forces stack scanning of active methods to aggressively remove unused code when only the given percentage of the code cache is free. The default value is 10%. -XX:-TieredCompilation Disables the use of tiered compilation. By default, this option is enabled. Only the Java HotSpot Server VM supports this option. -XX:+UseAES Enables hardware-based AES intrinsics for Intel, AMD, and SPARC hardware. Intel Westmere (2010 and newer), AMD Bulldozer (2011 and newer), and SPARC (T4 and newer) are the supported hardware. The -XX:+UseAES is used in conjunction with UseAESIntrinsics. Flags that control intrinsics now require the option -XX:+UnlockDiagnosticVMOptions . -XX:+UseAESIntrinsics
Enables -XX:+UseAES and -XX:+UseAESIntrinsics flags by default and are supported only for the Java HotSpot Server VM. To disable hardware-based AES intrinsics, specify -XX:-UseAES -XX:-UseAESIntrinsics . For example, to enable hardware AES, use the following flags:
Flags that control intrinsics now require the option -XX:+UnlockDiagnosticVMOptions . To support UseAES and UseAESIntrinsics flags, use the -server option to select the Java HotSpot Server VM. These flags aren’t supported on Client VM.
-XX:+UseCMoveUnconditionally Generates CMove (scalar and vector) instructions regardless of profitability analysis. -XX:+UseCodeCacheFlushing Enables flushing of the code cache before shutting down the compiler. This option is enabled by default. To disable flushing of the code cache before shutting down the compiler, specify -XX:-UseCodeCacheFlushing . -XX:+UseCondCardMark Enables checking if the card is already marked before updating the card table. This option is disabled by default. It should be used only on machines with multiple sockets, where it increases the performance of Java applications that rely on concurrent operations. Only the Java HotSpot Server VM supports this option. -XX:+UseCountedLoopSafepoints Keeps safepoints in counted loops. Its default value is false. -XX:+UseFMA Enables hardware-based FMA intrinsics for hardware where FMA instructions are available (such as, Intel, SPARC, and ARM64). FMA intrinsics are generated for the java.lang.Math.fma( a , b , c ) methods that calculate the value of ( a * b + c ) expressions. -XX:+UseRTMDeopt Autotunes RTM locking depending on the abort ratio. This ratio is specified by the -XX:RTMAbortRatio option. If the number of aborted transactions exceeds the abort ratio, then the method containing the lock is deoptimized and recompiled with all locks as normal locks. This option is disabled by default. The -XX:+UseRTMLocking option must be enabled. -XX:+UseRTMLocking
Generates Restricted Transactional Memory (RTM) locking code for all inflated locks, with the normal locking mechanism as the fallback handler. This option is disabled by default. Options related to RTM are available only for the Java HotSpot Server VM on x86 CPUs that support Transactional Synchronization Extensions (TSX).
RTM is part of Intel’s TSX, which is an x86 instruction set extension and facilitates the creation of multithreaded applications. RTM introduces the new instructions XBEGIN , XABORT , XEND , and XTEST . The XBEGIN and XEND instructions enclose a set of instructions to run as a transaction. If no conflict is found when running the transaction, then the memory and register modifications are committed together at the XEND instruction. The XABORT instruction can be used to explicitly abort a transaction and the XEND instruction checks if a set of instructions is being run in a transaction.
A lock on a transaction is inflated when another thread tries to access the same transaction, thereby blocking the thread that didn’t originally request access to the transaction. RTM requires that a fallback set of operations be specified in case a transaction aborts or fails. An RTM lock is a lock that has been delegated to the TSX’s system.
RTM improves performance for highly contended locks with low conflict in a critical region (which is code that must not be accessed by more than one thread concurrently). RTM also improves the performance of coarse-grain locking, which typically doesn’t perform well in multithreaded applications. (Coarse-grain locking is the strategy of holding locks for long periods to minimize the overhead of taking and releasing locks, while fine-grained locking is the strategy of trying to achieve maximum parallelism by locking only when necessary and unlocking as soon as possible.) Also, for lightly contended locks that are used by different threads, RTM can reduce false cache line sharing, also known as cache line ping-pong. This occurs when multiple threads from different processors are accessing different resources, but the resources share the same cache line. As a result, the processors repeatedly invalidate the cache lines of other processors, which forces them to read from main memory instead of their cache.
Enables hardware-based intrinsics for SHA crypto hash functions for SPARC hardware. The UseSHA option is used in conjunction with the UseSHA1Intrinsics , UseSHA256Intrinsics , and UseSHA512Intrinsics options.
The UseSHA and UseSHA*Intrinsics flags are enabled by default, and are supported only for Java HotSpot Server VM 64-bit on SPARC T4 and newer.
This feature is applicable only when using the sun.security.provider.Sun provider for SHA operations. Flags that control intrinsics now require the option -XX:+UnlockDiagnosticVMOptions .
To disable all hardware-based SHA intrinsics, specify the -XX:-UseSHA . To disable only a particular SHA intrinsic, use the appropriate corresponding option. For example: -XX:-UseSHA256Intrinsics .
-XX:+UseSHA1Intrinsics Enables intrinsics for SHA-1 crypto hash function. Flags that control intrinsics now require the option -XX:+UnlockDiagnosticVMOptions . -XX:+UseSHA256Intrinsics Enables intrinsics for SHA-224 and SHA-256 crypto hash functions. Flags that control intrinsics now require the option -XX:+UnlockDiagnosticVMOptions . -XX:+UseSHA512Intrinsics Enables intrinsics for SHA-384 and SHA-512 crypto hash functions. Flags that control intrinsics now require the option -XX:+UnlockDiagnosticVMOptions . -XX:+UseSuperWord Enables the transformation of scalar operations into superword operations. Superword is a vectorization optimization. This option is enabled by default. To disable the transformation of scalar operations into superword operations, specify -XX:-UseSuperWord . Only the Java HotSpot Server VM supports this option.
Advanced Serviceability Options for Java
These java options provide the ability to gather system information and perform extensive debugging.
Disables the mechanism that lets tools attach to the JVM. By default, this option is disabled, meaning that the attach mechanism is enabled and you can use diagnostics and troubleshooting tools such as jcmd , jstack , jmap , and jinfo .
Note: The tools such as jcmd, jinfo, jmap, and jstack shipped with the JDK aren’t supported when using the tools from one JDK version to troubleshoot a different JDK version.
Sets the path and file name for writing the heap dump provided by the heap profiler (HPROF) when the -XX:+HeapDumpOnOutOfMemoryError option is set. By default, the file is created in the current working directory, and it’s named java_pid<pid>.hprof where <pid> is the identifier of the process that caused the error. The following example shows how to set the default file explicitly ( %p represents the current process identifier):
Oracle Solaris, Linux, and macOS: The following example shows how to set the heap dump file to /var/log/java/java_heapdump.hprof :
Windows: The following example shows how to set the heap dump file to C:/log/java/java_heapdump.log :
Sets the path and file name to where log data is written. By default, the file is created in the current working directory, and it’s named hotspot.log .
Oracle Solaris, Linux, and macOS: The following example shows how to set the log file to /var/log/java/hotspot.log :
Windows: The following example shows how to set the log file to C:/log/java/hotspot.log :
Enables printing of a class instance histogram after one of the following events:
Oracle Solaris, Linux, and macOS: Control+Break
Windows: Control+C ( SIGTERM )
By default, this option is disabled.
Setting this option is equivalent to running the jmap -histo command, or the jcmd pid GC.class_histogram command, where pid is the current Java process identifier.
Enables printing of java.util.concurrent locks after one of the following events:
Oracle Solaris, Linux, and macOS: Control+Break
Windows: Control+C ( SIGTERM )
By default, this option is disabled.
Setting this option is equivalent to running the jstack -l command or the jcmd pid Thread.print -l command, where pid is the current Java process identifier.
-XX:+PrintFlagsRanges Prints the range specified and allows automatic testing of the values. See Validate Java Virtual Machine Flag Arguments. -XX:+PerfDataSaveToFile
If enabled, saves jstat binary data when the Java application exits. This binary data is saved in a file named hsperfdata_ pid, where pid is the process identifier of the Java application that you ran. Use the jstat command to display the performance data contained in this file as follows:
Advanced Garbage Collection Options for Java
These java options control how garbage collection (GC) is performed by the Java HotSpot VM.
-XX:+AggressiveHeap Enables Java heap optimization. This sets various parameters to be optimal for long-running jobs with intensive memory allocation, based on the configuration of the computer (RAM and CPU). By default, the option is disabled and the heap sizes are configured less aggressively. -XX:+AlwaysPreTouch Requests the VM to touch every page on the Java heap after requesting it from the operating system and before handing memory out to the application. By default, this option is disabled and all pages are committed as the application uses the heap space. -XX:+CMSClassUnloadingEnabled Enables class unloading when using the concurrent mark-sweep (CMS) garbage collector. This option is enabled by default. To disable class unloading for the CMS garbage collector, specify -XX:-CMSClassUnloadingEnabled . -XX:CMSExpAvgFactor= percent
Sets the percentage of time (0 to 100) used to weight the current sample when computing exponential averages for the concurrent collection statistics. By default, the exponential averages factor is set to 25%. The following example shows how to set the factor to 15%:
Sets the percentage of the old generation occupancy (0 to 100) at which to start a CMS collection cycle. The default value is set to -1. Any negative value (including the default) implies that the option -XX:CMSTriggerRatio is used to define the value of the initiating occupancy fraction.
The following example shows how to set the factor to 20%:
Sets the percentage (0 to 100) of the value specified by the option -XX:MinHeapFreeRatio that’s allocated before a CMS collection cycle commences. The default value is set to 80%.
The following example shows how to set the occupancy fraction to 75%:
Sets the number of threads used for concurrent GC. Sets threads to approximately 1/4 of the number of parallel garbage collection threads. The default value depends on the number of CPUs available to the JVM.
For example, to set the number of threads for concurrent GC to 2, specify the following option:
Sets the size of the regions into which the Java heap is subdivided when using the garbage-first (G1) collector. The value is a power of 2 and can range from 1 MB to 32 MB. The default region size is determined ergonomically based on the heap size with a goal of approximately 2048 regions.
The following example sets the size of the subdivisions to 16 MB:
Sets the percentage of the heap size to use as the maximum for the young generation size. The default value is 60 percent of your Java heap.
This is an experimental flag. This setting replaces the -XX:DefaultMaxNewGenPercent setting.
-XX:G1MixedGCCountTarget= number Sets the target number of mixed garbage collections after a marking cycle to collect old regions with at most G1MixedGCLIveThresholdPercent live data. The default is 8 mixed garbage collections. The goal for mixed collections is to be within this target number. -XX:G1MixedGCLiveThresholdPercent= percent
Sets the occupancy threshold for an old region to be included in a mixed garbage collection cycle. The default occupancy is 85 percent.
This is an experimental flag. This setting replaces the -XX:G1OldCSetRegionLiveThresholdPercent setting.
Sets the percentage of the heap to use as the minimum for the young generation size. The default value is 5 percent of your Java heap.
This is an experimental flag. This setting replaces the -XX:DefaultMinNewGenPercent setting.
-XX:G1OldCSetRegionThresholdPercent= percent Sets an upper limit on the number of old regions to be collected during a mixed garbage collection cycle. The default is 10 percent of the Java heap. -XX:G1ReservePercent= percent
Sets the percentage of the heap (0 to 50) that’s reserved as a false ceiling to reduce the possibility of promotion failure for the G1 collector. When you increase or decrease the percentage, ensure that you adjust the total Java heap by the same amount. By default, this option is set to 10%.
The following example sets the reserved heap to 20%:
Controls adaptive calculation of the old generation occupancy to start background work preparing for an old generation collection. If enabled, G1 uses -XX:InitiatingHeapOccupancyPercent for the first few times as specified by the value of -XX:G1AdaptiveIHOPNumInitialSamples , and after that adaptively calculates a new optimum value for the initiating occupancy automatically. Otherwise, the old generation collection process always starts at the old generation occupancy determined by -XX:InitiatingHeapOccupancyPercent .
The default is enabled.
Sets the initial size (in bytes) of the memory allocation pool. This value must be either 0, or a multiple of 1024 and greater than 1 MB. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, or g or G to indicate gigabytes. The default value is selected at run time based on the system configuration.
The following examples show how to set the size of allocated memory to 6 MB using various units:
If you set this option to 0, then the initial size is set as the sum of the sizes allocated for the old generation and the young generation. The size of the heap for the young generation can be set using the -XX:NewSize option.
Sets the initial amount of memory that the JVM will use for the Java heap before applying ergonomics heuristics as a percentage of the maximum amount determined as described in the -XX:MaxRAM option. The default value is 1.5625 percent.
The following example shows how to set the percentage of the initial amount of memory used for the Java heap:
Sets the initial survivor space ratio used by the throughput garbage collector (which is enabled by the -XX:+UseParallelGC and/or -XX:+UseParallelOldGC options). Adaptive sizing is enabled by default with the throughput garbage collector by using the -XX:+UseParallelGC and -XX:+UseParallelOldGC options, and the survivor space is resized according to the application behavior, starting with the initial value. If adaptive sizing is disabled (using the -XX:-UseAdaptiveSizePolicy option), then the -XX:SurvivorRatio option should be used to set the size of the survivor space for the entire execution of the application.
The following formula can be used to calculate the initial size of survivor space (S) based on the size of the young generation (Y), and the initial survivor space ratio (R):
The 2 in the equation denotes two survivor spaces. The larger the value specified as the initial survivor space ratio, the smaller the initial survivor space size.
By default, the initial survivor space ratio is set to 8. If the default value for the young generation space size is used (2 MB), then the initial size of the survivor space is 0.2 MB.
The following example shows how to set the initial survivor space ratio to 4:
Sets the percentage of the old generation occupancy (0 to 100) at which to start the first few concurrent marking cycles for the G1 garbage collector.
By default, the initiating value is set to 45%. A value of 0 implies nonstop concurrent GC cycles from the beginning until G1 adaptively sets this value.
See also the -XX:G1UseAdaptiveIHOP and -XX:G1AdaptiveIHOPNumInitialSamples options.
The following example shows how to set the initiating heap occupancy to 75%:
Sets a target for the maximum GC pause time (in milliseconds). This is a soft goal, and the JVM will make its best effort to achieve it. The specified value doesn’t adapt to your heap size. By default, for G1 the maximum pause time target is 200 milliseconds. The other generational collectors do not use a pause time goal by default.
The following example shows how to set the maximum target pause time to 500 ms:
Sets the maximum size (in byes) of the memory allocation pool. This value must be a multiple of 1024 and greater than 2 MB. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, or g or G to indicate gigabytes. The default value is selected at run time based on the system configuration. For server deployments, the options -XX:InitialHeapSize and -XX:MaxHeapSize are often set to the same value.
The following examples show how to set the maximum allowed size of allocated memory to 80 MB using various units:
The -XX:MaxHeapSize option is equivalent to -Xmx .
Sets the maximum allowed percentage of free heap space (0 to 100) after a GC event. If free heap space expands above this value, then the heap is shrunk. By default, this value is set to 70%.
Minimize the Java heap size by lowering the values of the parameters MaxHeapFreeRatio (default value is 70%) and MinHeapFreeRatio (default value is 40%) with the command-line options -XX:MaxHeapFreeRatio and -XX:MinHeapFreeRatio . Lowering MaxHeapFreeRatio to as low as 10% and MinHeapFreeRatio to 5% has successfully reduced the heap size without too much performance regression; however, results may vary greatly depending on your application. Try different values for these parameters until they’re as low as possible yet still retain acceptable performance.
Customers trying to keep the heap small should also add the option -XX:-ShrinkHeapInSteps . See Performance Tuning Examples for a description of using this option to keep the Java heap small by reducing the dynamic footprint for embedded applications.
Sets the maximum amount of native memory that can be allocated for class metadata. By default, the size isn’t limited. The amount of metadata for an application depends on the application itself, other running applications, and the amount of memory available on the system.
The following example shows how to set the maximum class metadata size to 256 MB:
Sets the maximum amount of memory that the JVM may use for the Java heap before applying ergonomics heuristics. The default value is the maximum amount of available memory to the JVM process or 128 GB, whichever is lower.
The maximum amount of available memory to the JVM process is the minimum of the machine’s physical memory and any constraints set by the environment (e.g. container).
Specifying this option disables automatic use of compressed oops if the combined result of this and other options influencing the maximum amount of memory is larger than the range of memory addressable by compressed oops. See -XX:UseCompressedOops for further information about compressed oops.
The following example shows how to set the maximum amount of available memory for sizing the Java heap to 2 GB:
Sets the maximum amount of memory that the JVM may use for the Java heap before applying ergonomics heuristics as a percentage of the maximum amount determined as described in the -XX:MaxRAM option. The default value is 25 percent.
Specifying this option disables automatic use of compressed oops if the combined result of this and other options influencing the maximum amount of memory is larger than the range of memory addressable by compressed oops. See -XX:UseCompressedOops for further information about compressed oops.
The following example shows how to set the percentage of the maximum amount of memory used for the Java heap:
Sets the maximum amount of memory that the JVM may use for the Java heap before applying ergonomics heuristics as a percentage of the maximum amount determined as described in the -XX:MaxRAM option for small heaps. A small heap is a heap of approximately 125 MB. The default value is 50 percent.
The following example shows how to set the percentage of the maximum amount of memory used for the Java heap for small heaps:
Sets the maximum tenuring threshold for use in adaptive GC sizing. The largest value is 15. The default value is 15 for the parallel (throughput) collector, and 6 for the CMS collector.
The following example shows how to set the maximum tenuring threshold to 10:
Sets the minimum allowed percentage of free heap space (0 to 100) after a GC event. If free heap space falls below this value, then the heap is expanded. By default, this value is set to 40%.
Minimize Java heap size by lowering the values of the parameters MaxHeapFreeRatio (default value is 70%) and MinHeapFreeRatio (default value is 40%) with the command-line options -XX:MaxHeapFreeRatio and -XX:MinHeapFreeRatio . Lowering MaxHeapFreeRatio to as low as 10% and MinHeapFreeRatio to 5% has successfully reduced the heap size without too much performance regression; however, results may vary greatly depending on your application. Try different values for these parameters until they’re as low as possible, yet still retain acceptable performance.
Customers trying to keep the heap small should also add the option -XX:-ShrinkHeapInSteps . See Performance Tuning Examples for a description of using this option to keep the Java heap small by reducing the dynamic footprint for embedded applications.
Sets the minimum size (in bytes) of the memory allocation pool. This value must be either 0, or a multiple of 1024 and greater than 1 MB. Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, or g or G to indicate gigabytes. The default value is selected at run time based on the system configuration.
The following examples show how to set the mimimum size of allocated memory to 6 MB using various units:
If you set this option to 0, then the minimum size is set to the same value as the initial size.
Sets the ratio between young and old generation sizes. By default, this option is set to 2. The following example shows how to set the young-to-old ratio to 1:
Sets the initial size (in bytes) of the heap for the young generation (nursery). Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, or g or G to indicate gigabytes.
The young generation region of the heap is used for new objects. GC is performed in this region more often than in other regions. If the size for the young generation is too low, then a large number of minor GCs are performed. If the size is too high, then only full GCs are performed, which can take a long time to complete. It is recommended that you keep the size for the young generation greater than 25% and less than 50% of the overall heap size.
The following examples show how to set the initial size of the young generation to 256 MB using various units:
The -XX:NewSize option is equivalent to -Xmn .
Sets the number of the stop-the-world (STW) worker threads. The default value depends on the number of CPUs available to the JVM and the garbage collector selected.
For example, to set the number of threads for G1 GC to 2, specify the following option:
Sets the amount of time (in milliseconds) a softly reachable object is kept active on the heap after the last time it was referenced. The default value is one second of lifetime per free megabyte in the heap. The -XX:SoftRefLRUPolicyMSPerMB option accepts integer values representing milliseconds per one megabyte of the current heap size (for Java HotSpot Client VM) or the maximum possible heap size (for Java HotSpot Server VM). This difference means that the Client VM tends to flush soft references rather than grow the heap, whereas the Server VM tends to grow the heap rather than flush soft references. In the latter case, the value of the -Xmx option has a significant effect on how quickly soft references are garbage collected.
The following example shows how to set the value to 2.5 seconds:
Incrementally reduces the Java heap to the target size, specified by the option -XX:MaxHeapFreeRatio . This option is enabled by default. If disabled, then it immediately reduces the Java heap to the target size instead of requiring multiple garbage collection cycles. Disable this option if you want to minimize the Java heap size. You will likely encounter performance degradation when this option is disabled.
See Performance Tuning Examples for a description of using the MaxHeapFreeRatio option to keep the Java heap small by reducing the dynamic footprint for embedded applications.
Identifies String objects reaching the specified age that are considered candidates for deduplication. An object’s age is a measure of how many times it has survived garbage collection. This is sometimes referred to as tenuring.
Note: String objects that are promoted to an old heap region before this age has been reached are always considered candidates for deduplication. The default value for this option is 3 . See the -XX:+UseStringDeduplication option.
Sets the ratio between eden space size and survivor space size. By default, this option is set to 8. The following example shows how to set the eden/survivor space ratio to 4:
Sets the desired percentage of survivor space (0 to 100) used after young garbage collection. By default, this option is set to 50%.
The following example shows how to set the target survivor space ratio to 30%:
Sets the initial size (in bytes) of a thread-local allocation buffer (TLAB). Append the letter k or K to indicate kilobytes, m or M to indicate megabytes, or g or G to indicate gigabytes. If this option is set to 0, then the JVM selects the initial size automatically.
The following example shows how to set the initial TLAB size to 512 KB:
Enables the use of the parallel scavenge garbage collector (also known as the throughput collector) to improve the performance of your application by leveraging multiple processors.
By default, this option is disabled and the default collector is used. If it’s enabled, then the -XX:+UseParallelOldGC option is automatically enabled, unless you explicitly disable it.
-XX:+UseParallelOldGC Enables the use of the parallel garbage collector for full GCs. By default, this option is disabled. Enabling it automatically enables the -XX:+UseParallelGC option. -XX:+UseSerialGC Enables the use of the serial garbage collector. This is generally the best choice for small and simple applications that don’t require any special functionality from garbage collection. By default, this option is disabled and the default collector is used. -XX:+UseSHM
Linux only: Enables the JVM to use shared memory to set up large pages.
See Large Pages for setting up large pages.
Enables string deduplication. By default, this option is disabled. To use this option, you must enable the garbage-first (G1) garbage collector.
String deduplication reduces the memory footprint of String objects on the Java heap by taking advantage of the fact that many String objects are identical. Instead of each String object pointing to its own character array, identical String objects can point to and share the same character array.
-XX:+UseTLAB Enables the use of thread-local allocation blocks (TLABs) in the young generation space. This option is enabled by default. To disable the use of TLABs, specify the option -XX:-UseTLAB . -XX:+UseZGC
Enables the use of the Z garbage collector. This garbage collector is best for providing lowest latency with large Java heaps at some throughput cost. This is an experimental garbage collector, you need to specify -XX:+UnlockExperimentalVMOptions before -XX:+UseZGC on the command line.
Deprecated Java Options
These java options are deprecated and might be removed in a future JDK release. They’re still accepted and acted upon, but a warning is issued when they’re used.
-Xfuture Enables strict class-file format checks that enforce close conformance to the class-file format specification. Developers should use this flag when developing new code. Stricter checks may become the default in future releases. -Xloggc: filename
Sets the file to which verbose GC events information should be redirected for logging. The -Xloggc option overrides -verbose:gc if both are given with the same java command. -Xloggc: filename is replaced by -Xlog:gc: filename. See Enable Logging with the JVM Unified Logging Framework.
-XX:+FailOverToOldVerifier Enables automatic failover to the old verifier when the new type checker fails. By default, this option is disabled and it’s ignored (that is, treated as disabled) for classes with a recent bytecode version. You can enable it only for classes with older versions of the bytecode. -XX:+FlightRecorder Enables the use of Java Flight Recorder (JFR) during the runtime of the application. Since JDK 8u40 this option has not been required to use JFR. -XX:InitialRAMFraction= ratio
Sets the initial amount of memory that the JVM may use for the Java heap before applying ergonomics heuristics as a ratio of the maximum amount determined as described in the -XX:MaxRAM option. The default value is 64.
Use the option -XX:InitialRAMPercentage instead.
Sets the maximum amount of memory that the JVM may use for the Java heap before applying ergonomics heuristics as a fraction of the maximum amount determined as described in the -XX:MaxRAM option. The default value is 4.
Specifying this option disables automatic use of compressed oops if the combined result of this and other options influencing the maximum amount of memory is larger than the range of memory addressable by compressed oops. See -XX:UseCompressedOops for further information about compressed oops.
Use the option -XX:MaxRAMPercentage instead.
Sets the maximum amount of memory that the JVM may use for the Java heap before applying ergonomics heuristics as a fraction of the maximum amount determined as described in the -XX:MaxRAM option for small heaps. A small heap is a heap of approximately 125 MB. The default value is 2.
Use the option -XX:MinRAMPercentage instead.
Enables tracing of classes as they are loaded. By default, this option is disabled and classes aren’t traced.
The replacement Unified Logging syntax is -Xlog:class+load= level. See Enable Logging with the JVM Unified Logging Framework
Use level= info for regular information, or level= debug for additional information. In Unified Logging syntax, -verbose:class equals -Xlog:class+load=info,class+unload=info .
Enables tracing of all loaded classes in the order in which they’re referenced. By default, this option is disabled and classes aren’t traced.
The replacement Unified Logging syntax is -Xlog:class+preorder=debug . See Enable Logging with the JVM Unified Logging Framework.
Enables tracing of constant pool resolutions. By default, this option is disabled and constant pool resolutions aren’t traced.
The replacement Unified Logging syntax is -Xlog:class+resolve=debug . See Enable Logging with the JVM Unified Logging Framework.
Enables tracing of the loader constraints recording. By default, this option is disabled and loader constraints recording isn’t traced.
The replacement Unified Logging syntax is -Xlog:class+loader+constraints=info . See Enable Logging with the JVM Unified Logging Framework.
-XX:+UseConcMarkSweepGC Enables the use of the CMS garbage collector for the old generation. CMS is an alternative to the default garbage collector (G1), which also focuses on meeting application latency requirements. By default, this option is disabled and the collector is selected automatically based on the configuration of the machine and type of the JVM. The CMS garbage collector is deprecated.
Obsolete Java Options
These java options are still accepted but ignored, and a warning is issued when they’re used.
-XX:+UseMembar Enabled issuing membars on thread-state transitions. This option was disabled by default on all platforms except ARM servers, where it was enabled. -XX:MaxPermSize= size Sets the maximum permanent generation space size (in bytes). This option was deprecated in JDK 8 and superseded by the -XX:MaxMetaspaceSize option. -XX:PermSize= size Sets the space (in bytes) allocated to the permanent generation that triggers a garbage collection if it’s exceeded. This option was deprecated in JDK 8 and superseded by the -XX:MetaspaceSize option.
Removed Java Options
These java options have been removed in JDK 13 and using them results in an error of:
For the lists and descriptions of options removed in previous releases see the Removed Java Options section in: