JVM 参数众多,我们常在启动一个 Java 程序时通过命令行(例如:java -jar app.jar
)指定各种参数选项。很多同学就会对此感到疑惑,为什么有时候要用 -D
,有时候却要用 -X
,还有些时候用的却是 -XX
呢?
今天,我就在这篇文章中讲一讲这些选项之间的差异。看完这篇文章之后,你将学到 JVM 选项的主要分类、不同分类的选项的主要用途,以及如何找出 JVM 支持的各种配置项。
想直接知道答案的同学可以直接跳到文章结尾。
JVM 选项分类
JVM 其实支持三种类型的选项:标准选项(standard options)、非标准选项(non-standard options,又叫 extra-options)和高级选项(advanced options)。之所以有这么多选项,是因为 JVM 只是一个规范,它有不同的实现,例如 HotSpot、OpenJ9、GraalVM、Azul Zing 等。不同的 JVM 实现支持的选项会有所不同,但是有些选项是所有的 JVM 实现都会支持的,这类选项就是标准选项。
标准选项
标准选项是所有 JVM 实现都会支持的。打开控制台,输入 java
,你不仅能看到 java
命令的使用手册,还能看到你机器上默认的 JVM 所支持的所有标准选项:
~$ java
Usage: java [options] <mainclass> [args...]
(to execute a class)
or java [options] -jar <jarfile> [args...]
(to execute a jar file)
or java [options] -m <module>[/<mainclass>] [args...]
java [options] --module <module>[/<mainclass>] [args...]
(to execute the main class in a module)
or java [options] <sourcefile> [args]
(to execute a single source-file program)
Arguments following the main class, source file, -jar <jarfile>,
-m or --module <module>/<mainclass> are passed as the arguments to
main class.
where options include:
-zero to select the "zero" VM
-dcevm to select the "dcevm" VM
-cp <class search path of directories and zip/jar files>
-classpath <class search path of directories and zip/jar files>
--class-path <class search path of directories and zip/jar files>
A : separated list of directories, JAR archives,
and ZIP archives to search for class files.
-p <module path>
--module-path <module path>...
A : separated list of directories, each directory
is a directory of modules.
--upgrade-module-path <module path>...
A : separated list of directories, each directory
is a directory of modules that replace upgradeable
modules in the runtime image
--add-modules <module name>[,<module name>...]
root modules to resolve in addition to the initial module.
<module name> can also be ALL-DEFAULT, ALL-SYSTEM,
ALL-MODULE-PATH.
--enable-native-access <module name>[,<module name>...]
modules that are permitted to perform restricted native operations.
<module name> can also be ALL-UNNAMED.
--list-modules
list observable modules and exit
-d <module name>
--describe-module <module name>
describe a module and exit
--dry-run create VM and load main class but do not execute main method.
The --dry-run option may be useful for validating the
command-line options such as the module system configuration.
--validate-modules
validate all modules and exit
The --validate-modules option may be useful for finding
conflicts and other errors with modules on the module path.
-D