JVM Runtime Parameters

JVM Runtime Parameters

1.JVM parameter options

Official address: https://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html

Type 1: Standard parameter options

> java -help
 usage: java [-options] class [args...]
           (Execution Class)
   or  java [-options] -jar jarfile [args...]
           (implement jar file)
Options include:
    -d32          Using a 32-bit data model (If available)
    -d64          Using a 64-bit data model (If available)
    -server       Choice "server" VM
                  default VM yes server.

    -cp <Catalog and zip/jar Class Search Path for Files>
    -classpath <Catalog and zip/jar Class Search Path for Files>
                  use ; Separated directories, JAR archives
                  and ZIP File List, Used to search for class files.
                  Set System Properties
                  Enable verbose output
    -version      Output product version and exit
                  warning: This feature is obsolete, Will be in
                  Deleted in future releases.
                  The specified version is required to run
    -showversion  Output product version and continue
    -jre-restrict-search | -no-jre-restrict-search
                  warning: This feature is obsolete, Will be in
                  Deleted in future releases.
                  Include in version search/Exclude User Only JRE
    -? -help      Output this help message
    -X            Help with Output Nonstandard Options
                  Enable assertions at specified granularity
                  Disable assertions with specified granularity
    -esa | -enablesystemassertions
                  Enable System Assertions
    -dsa | -disablesystemassertions
                  Disable System Assertions
                  Load Native Agent Library <libname>, for example -agentlib:hprof
                  See also -agentlib:jdwp=help and -agentlib:hprof=help
                  Load local proxy library by full path name
                  Load Java Programming language proxy, see also java.lang.instrument
                  Display the startup screen with the specified image
 For more information, see also http://www.oracle.com/technetwork/java/javase/documentation/index.html. 

Server mode and Client mode

The Hotspot JVM has two modes, server and client, which are set through-server and-client modes, respectively.

  • On 32-bit systems, the client type JVM is used by default. To use Server mode, the machine is configured with at least two CPU s and more than 2G of physical memory. client mode works for desktop applications that require less memory, using Serial Serial Garbage Collector by default
  • On 64-bit systems, only server-mode JVM s are supported, suitable for applications requiring large memory, using a parallel garbage collector by default

Official address: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/server-class.html

How do I know which mode the system uses by default?

With the java-version command: you can see the word Server VM, indicating that the current system is using Server mode

> java -version
java version "1.8.0_101"
Java(TM) SE Runtime Environment (build 1.8.0_101-b13)
Java HotSpot(TM) 64-Bit Server VM (build 25.101-b13, mixed mode)

Type 2: -X Parameter Options

> java -X
    -Xmixed           Mixed mode execution (default)
    -Xint             Interpret mode execution only
    -Xbootclasspath:<use ; Separated directories and zip/jar file>
                      Set search paths to guide classes and resources
    -Xbootclasspath/a:<use ; Separated directories and zip/jar file>
                      Attached at the end of the boot class path
    -Xbootclasspath/p:<use ; Separated directories and zip/jar file>
                      Place before boot class path
    -Xdiag            Show additional diagnostic messages
    -Xnoclassgc       Disable Class Garbage Collection
    -Xincgc           Enable Incremental Garbage Collection
    -Xloggc:<file>    take GC Status Record in File (With timestamp)
    -Xbatch           Disable background compilation
    -Xms<size>        Set Initial Java Heap size
    -Xmx<size>        Set maximum Java Heap size
    -Xss<size>        Set up Java Thread Stack Size
    -Xprof            output cpu Profile data
    -Xfuture          Enable the strictest checks, Expected future defaults
    -Xrs              reduce Java/VM Use of operating system signals (See documentation)
    -Xcheck:jni       Yes JNI Function performs other checks
    -Xshare:off       Do not attempt to use shared class data
    -Xshare:auto      Use shared class data where possible (default)
    -Xshare:on        Require shared class data, Otherwise it will fail.
    -XshowSettings    Show all settings and continue
                      Show all settings and continue
    -XshowSettings:vm Show all and vm Related Settings and Continue
                      Show all property settings and continue
                      Show all locale related settings and continue

-X Options are nonstandard options, If changed, No further notice is required.

How do I know that the JVM defaults to mixed mode?

Similarly, with the java-version command, you can see the word mixed mode, which means that the current system is using mixed mode

Type 3: -XX parameter options

Boolean Type Format

-XX:+<option>  Enable option attribute
-XX:-<option>  Disable option attribute

Non-Boolean Type Format

-XX:<option>=<number>  Set up option Numeric values, which can be in units such as k/K/m/M/g/G
-XX:<option>=<string>  Set up option Character Value

2. Add JVM parameter options

Configuration in eclipse and idea doesn't have to be said much. Configuration in VM Options in Run Configurations is much the same.

Run jar package

java -Xms100m -Xmx100m -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps -jar demo.jar

Tomcat runs the war package

# catalina.sh Add under linux
JAVA_OPTS="-Xms512M -Xmx1024M"
# catalina.bat Add under windows
set "JAVA_OPTS=-Xms512M -Xmx1024M"

Program running

# Setting Boolean type parameters
jinfo -flag [+|-]<name> <pid>
# Setting non-Boolean type parameters
jinfo -flag <name>=<value> <pid>

3. Common JVM parameter options

3.1. XX Options and Values for Print Settings

-XX:+PrintCommandLineFlags Program Runtime JVM Default Settings or User Manual Settings XX option
-XX:+PrintFlagsInitial Print all XX Default value of option
-XX:+PrintFlagsFinal Print all XX Actual value of option
-XX:+PrintVMOptions Print JVM Parameters

3.2. Memory size settings such as stack, stack, method area

# Stack
-Xss128k <==> -XX:ThreadStackSize=128k Set the thread stack size to 128 K

# heap
-Xms2048m <==> -XX:InitialHeapSize=2048m Set up JVM Initial heap memory 2048 M
-Xmx2048m <==> -XX:MaxHeapSize=2048m Set up JVM Maximum heap memory 2048 M
-Xmn2g <==> -XX:NewSize=2g -XX:MaxNewSize=2g Set younger generation size to 2 G
-XX:SurvivorRatio=8 Set up Eden Zone and Survivor Zone ratio, default to 8
-XX:NewRatio=2 Set the ratio of older generation to younger generation, default is 2
-XX:+UseAdaptiveSizePolicy Set Size Scale Adaptive, on by default
-XX:PretenureSizeThreadshold=1024 Set to allow objects greater than this threshold to be allocated directly to older generations, only to Serial,ParNew Collector is valid
-XX:MaxTenuringThreshold=15 Set age limit for new generation promotion to older generation, default is 15
-XX:TargetSurvivorRatio Set up MinorGC After the end Survivor Expected proportion of area occupied space

# Method Area
-XX:MetaspaceSize / -XX:PermSize=256m Set Metaspace/Permanent generation initial value is 256 M
-XX:MaxMetaspaceSize / -XX:MaxPermSize=256m Set Metaspace/Maximum Permanent Generation is 256 M
-XX:+UseCompressedOops Using compressed objects
-XX:+UseCompressedClassPointers Use Compressed Class Pointer
-XX:CompressedClassSpaceSize Set up Klass Metaspace Size, default 1 G

# Direct memory
-XX:MaxDirectMemorySize Appoint DirectMemory Capacity, equal by default Java Heap maximum

3.3. OutOfMemory-related options

-XX:+HeapDumpOnOutMemoryError Memory appears OOM Generated on Heap Dump files, which are mutually exclusive
-XX:+HeapDumpBeforeFullGC Appear FullGC Generated on Heap Dump files, which are mutually exclusive
-XX:HeapDumpPath=<path> Appoint heap Storage path of dump file, default current directory
-XX:OnOutOfMemoryError=<path> Specify the path to the feasibility program or script when OOM Execute script on

3.4. Garbage Collector-related Options

First, you need to understand how garbage collectors work together

  • The red dashed line indicates that Deprecate was deleted at jdk8 and jdk9
  • The green dashed line indicates Deprecate at jdk14
  • A green dashed box indicates that Deprecate was deleted at jdk9 and jdk14

# Serial Recycler
-XX:+UseSerialGC  Use by younger generations Serial GC, Older generation use Serial Old GC
# ParNew Recycler
-XX:+UseParNewGC  Use by younger generations ParNew GC
-XX:ParallelGCThreads  Sets the number of threads for the younger generation parallel collector.
    In general, it's best to work with CPU Equal number to avoid too many threads affecting garbage collection performance.

$$ ParallelGCThreads = \begin{cases} CPU_Count & \text (CPU_Count <= 8) \ 3 + (5 * CPU_Count / 8) & \text (CPU_Count > 8) \end{cases} $$

# Parallel Recycler
-XX:+UseParallelGC  Use by younger generations Parallel Scavenge GC,Mutual activation
-XX:+UseParallelOldGC  Older generation use Parallel Old GC,Mutual activation
-XX:MaxGCPauseMillis  Set the maximum pause time for the garbage collector (i.e. STW Time), in milliseconds.
    In order to keep the pause time as low as possible MaxGCPauseMills Within this range, the collector adjusts during operation Java Heap size or some other parameter.
    For users, the shorter the pause time, the better the experience; However, the server side focuses on high concurrency and overall throughput.
    So the server side fits Parallel,Control. Use caution with this parameter.
-XX:GCTimeRatio  Garbage collection time as a percentage of total time (1) / (N+1)),Size used to measure throughput
    Range of values (0,100),Default value 99, i.e. no more than 1 garbage collection time%. 
    With the previous-XX: MaxGCPauseMillis The parameters are somewhat contradictory. The longer the pause, Radio Parameters can easily exceed the set scale.
-XX:+UseAdaptiveSizePolicy  Set up Parallel Scavenge The collector has an adaptive adjustment strategy.
    In this mode, the size of the younger generation, Eden and Survivor Parameters such as proportions, age of objects promoted to older generations, and so on, are automatically adjusted to achieve a balance between heap size, throughput, and pause time.
    In cases where manual tuning is difficult, this adaptive approach can be used directly to specify only the maximum heap and target throughput of the virtual machine (VM). GCTimeRatio)And pause time ( MaxGCPauseMills),Let the virtual machine do the tuning on its own.
# CMS Recycler
-XX:+UseConcMarkSweepGC  Use by younger generations CMS GC. 
    When this parameter is turned on, the-XX: +UseParNewGC Open. That is: ParNew(Young Zone)+ CMS(Old Zone)+ Serial Old Combination
-XX:CMSInitiatingOccupanyFraction  Set a threshold for heap memory usage and start recycling once it is reached. JDK5 The default value for previous versions is 68, DK6 The default value for versions above and above is 92%. 
    If memory growth is slow, you can set a slightly larger value, which can effectively reduce the threshold CMS Trigger frequency and fewer recycles in older generations can significantly improve application performance.
    Conversely, if application memory usage is growing rapidly, this threshold should be lowered to avoid frequent triggering of older serial collectors.
    Therefore, this option can be used to effectively reduce the Fu1l GC Number of executions.
-XX:+UseCMSInitiatingOccupancyOnly  Is it dynamically adjustable so that CMS Keep pressing CMSInitiatingOccupancyFraction Set Value Start
-XX:+UseCMSCompactAtFullCollection  Used to specify completion of execution Full GC Then compress the memory space
    This prevents memory fragmentation. However, since the memory compression collation process cannot be executed concurrently, the problem is that the pause time becomes longer.
-XX:CMSFullGCsBeforeCompaction  Set how many times to execute Full GC Then compress the memory space.
-XX:ParallelCMSThreads  Set up CMS Number of threads.
    CMS The default number of threads started is(ParallelGCThreads+3)/4,ParallelGCThreads Is the number of threads in the younger generation of parallel collectors.
    When CPU When resources are tight, CMS Impact of collector threads, application performance can be very poor during the garbage collection phase.
-XX:ConcGCThreads  Sets the number of threads for concurrent garbage collection, which by default is based on ParallelGCThreads Calculated
-XX:+CMSScavengeBeforeRemark  force hotspot stay cms remark Do it once before the stage minor gc,For improvement remark Speed of Stage
-XX:+CMSClassUnloadingEnable  Enable recycling if available Perm Zone( JDK8 Before)
-XX:+CMSParallelInitialEnabled  For opening CMS initial-mark Stages are marked with multiple threads
    Used to speed up marking, in Java8 Start already turned on by default
-XX:+CMSParallelRemarkEnabled  User Open CMS remark Stage is marked as multithreaded and turned on by default
    These two parameters are user specified hotspot Virtual Execution System.gc()Use when CMS cycle
-XX:+CMSPrecleaningEnabled  Appoint CMS Do you need to Pre cleaning stage
# G1 Recycler
-XX:+UseG1GC Specify use manually G1 The collector performs memory recycling tasks.
-XX:G1HeapRegionSize Set Each Region Size.
    Value is a power of 2 and range is 1 MB To 32 MB Between, the goal is based on the smallest Java The heap size is divided into about 2048 regions. The default is 1 for heap memory/2000. 
-XX:MaxGCPauseMillis  Set the maximum you want to reach GC Stop time indicator ( JVM Will try to do it, but not guarantee it). The default value is 200 ms
-XX:ParallelGCThread  Set up STW time GC The value of the number of threads. Set up to 8
-XX:ConcGCThreads  Sets the number of threads marked for concurrency. take n Set to the number of parallel garbage collection threads ( ParallelGCThreads)1/4 About.
-XX:InitiatingHeapOccupancyPercent Set Trigger Concurrency GC Periodic Java Heap occupancy threshold. If this value is exceeded, trigger GC. The default value is 45.
-XX:G1NewSizePercent  Minimum percentage of total heap memory consumed by the new generation (default 5)%)
-XX:G1MaxNewSizePercent  Maximum percentage of total heap memory consumed by the new generation (default 60)%)
-XX:G1ReservePercent=10  Keep memory area, prevent to space(Survivor In to Zone) Overflow

How do I choose a garbage collector?

  • Give priority to JVM adapting, adjust heap size
  • Serial collector: Memory less than 100M; Single-core, single-machine program with no pause time requirement
  • Parallel collector: multi-CPU, high throughput, allowed pause time more than 1 second
  • Concurrent collectors: multiple CPU s, low pause times, fast response (e.g. no more than a second delay, e.g. Internet applications)
  • Officially recommended G1 for high performance. Now the Internet projects are basically using G1

Special instructions:

  • No best collector, no omnipotent collector
  • Tuning is always for specific scenarios, specific needs, and there is no one-off collector

3.5. GC log-related options

-XX:+PrintGC <==> -verbose:gc  Print brief log information
-XX:+PrintGCDetails            Print detailed log information
-XX:+PrintGCTimeStamps  Printer starts to GC When it happens, match-XX:+PrintGCDetails Use
-XX:+PrintGCDateStamps  Print GC Timestamp at occurrence, match-XX:+PrintGCDetails Use
-XX:+PrintHeapAtGC  Print GC Heap information before and after, as shown below
-Xloggc:<file> output GC Import files under specified path

-XX:+TraceClassLoading  Monitor Class Loading
-XX:+PrintGCApplicationStoppedTime  Print GC The pause time of the thread at
-XX:+PrintGCApplicationConcurrentTime  Apply uninterrupted execution time before printing garbage collection
-XX:+PrintReferenceGC How many different reference types are recycled by printing
-XX:+PrintTenuringDistribution  Print JVM At every time MinorGC Currently used after Survivor Age distribution of objects in
-XX:+UseGCLogFileRotation Enable GC Automatic dump of log files
-XX:NumberOfGCLogFiles=1  Set up GC Number of loops for log files
-XX:GCLogFileSize=1M  Set up GC Size of log file

3.6. Other parameters

-XX:+DisableExplicitGC  Disable hotspot implement System.gc(),Disabled by default
-XX:ReservedCodeCacheSize=<n>[g|m|k],-XX:InitialCodeCacheSize=<n>[g|m|k]  Specify the size of the code cache
-XX:+UseCodeCacheFlushing  Discard some compiled code to avoid code cache overrun JVM switch to interpreted-only Situation
-XX:+DoEscapeAnalysis  Turn on escape analysis
-XX:+UseBiasedLocking  Open deflection lock
-XX:+UseLargePages  Open Use Big Page
-XX:+PrintTLAB  Print TLAB Usage
-XX:TLABSize  Set up TLAB Size

4. Obtain JVM parameters from Java code

Java provides the java.lang.management package for monitoring and managing Java virtual machines and other components in the Java runtime, which allows local or remote monitoring and management of running Java virtual machines. The ManagementFactory class is more common among them, and the Runtime class can get related data such as memory, CPU cores, etc. By using these api s, you can monitor the heap memory usage of the application server, set some thresholds for alerts, and so on.

public class MemoryMonitor {
    public static void main(String[] args) {
        MemoryMXBean memorymbean = ManagementFactory.getMemoryMXBean();
        MemoryUsage usage = memorymbean.getHeapMemoryUsage();
        System.out.println("INIT HEAP: " + usage.getInit() / 1024 / 1024 + "m");
        System.out.println("MAX HEAP: " + usage.getMax() / 1024 / 1024 + "m");
        System.out.println("USE HEAP: " + usage.getUsed() / 1024 / 1024 + "m");
        System.out.println("\nFull Information:");
        System.out.println("Heap Memory Usage: " + memorymbean.getHeapMemoryUsage());
        System.out.println("Non-Heap Memory Usage: " + memorymbean.getNonHeapMemoryUsage());

        System.out.println("=======================adopt java To get the relevant system state============================ ");
        System.out.println("Current heap memory size totalMemory " + (int) Runtime.getRuntime().totalMemory() / 1024 / 1024 + "m");// Current heap memory size
        System.out.println("Free heap memory size freeMemory " + (int) Runtime.getRuntime().freeMemory() / 1024 / 1024 + "m");// Free heap memory size
        System.out.println("Maximum Total Available Heap Memory maxMemory " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "m");// Maximum Total Available Heap Memory Size


Copyright: Knowledge Sharing Signature 4.0 Licensing under International License Agreement Links: https://lixj.fun/archives/jvm Runtime parameters

Posted by netdog on Tue, 26 Jul 2022 04:45:40 +0930