Note source: Silicon Valley JVM complete tutorial, millions of playback, the peak of the entire network (Song Hongkang details Java virtual machine)

Update: gitee.com/vectorx/NOT…

Codechina.csdn.net/qq_35925558…

Github.com/uxiahnan/NO…

[TOC]

4. JVM runtime parameters

4.1. JVM parameter options

Website address: docs.oracle.com/javase/8/do…

4.1.1. Type 1: Standard parameter options

> java -helpJava [-options] class [args...] [-options] -jar jarfile [args...] (Execute jar file) The options include: -d32 uses 32-bit data model (if available) -D64 uses 64-bit data model (if available) -server Select "server" VM default VM is server. -cp < class search path for directories and zip/ JAR files > -classpath < class search path for directories and zip/ JAR files > used; A separated list of directories, JAR files, and ZIP files for searching class files. - D < name > = > < value set system properties - verbose: [class | gc | jni] enable verbose output - version output product version and exit - version: < value > warning: this function has been out of date and will be deleted in future releases. You need to specify the version to run - showversion output product release and continue - jre - restrict - search | - no - jre - restrict - search warning: this function has been out of date, will be deleted in future releases. Include/exclude user-specific JRE in version search -? -help output the help message - X output non-standard options help - ea [: < packagename >... | : < classname >] - enableassertions [: < packagename >... | : < classname >] According to the specified size to enable assertion - da [: < packagename >... | : < classname >] -disableassertions [: < packagename >... | : < classname >] assertion - esa | disabled has the specified size - enablesystemassertions enable system assertion - dsa | - disablesystemassertions disable system assertion - agentlib: < libname > / = < option > loading native agents library < libname >, For example -agentlib:hprof See also -agentlib: JDWP =help and -agentlib:hprof=help -agentPath :<pathname>[=< options >] Load the local agent library with the full pathname -JavaAgent :< jarPath >[=< options >] Load the Java programming language agent, see java.lang. instrument-Splash :< Imagepath > For more information about displaying the boot screen with the specified image, Please refer to http://www.oracle.com/technetwork/java/javase/documentation/index.html.Copy the code

Server mode and Client mode

Hotspot JVM has two modes, server and client, set through -server and -client modes respectively

  • On 32-bit systems, Client type JVMS are used by default. To use Server mode, the machine must be configured with at least two cpus and two gigabytes of physical memory. The client mode is suitable for desktop applications with small memory requirements, and the Serial Serial garbage collector is used by default
  • On 64-bit systems, only Server mode JVMS are supported, suitable for applications requiring large memory, and the parallel garbage collector is used by default

Website address: docs.oracle.com/javase/8/do…

How do you know which mode is used by default?

Using the Java -version command, you can view Server VM, indicating that the current system is in Server mode

> java -versionJava version "1.8.0_201" Java(TM) SE Runtime Environment (build 1.8.0_201-B09) Java HotSpot(TM) 64-bit Server VM (build 25.201 - b09, mixed mode)Copy the code

4.1.2. Type 2: -x parameter option

> java -X-xmixed mode execution (default) -xint only explain mode execution -xbootCLASspath :< with; > Set the search path to boot classes and resources -xbootclasspath /a:< with; Separated directories and zip/ JAR files > appended at the end of the bootclasspath -xbootclasspath /p:< with; Separated directories and ZIP/JAR files > placed before the boot classpath -Xdiag displays additional diagnostic messages -Xnoclassgc disables class garbage collection -Xincgc enables incremental garbage collection -Xloggc:<file> Records GC status in a file (with time stamps) -xbatch Disables background compilation -xms <size> Sets the initial Java heap size -xmx <size> Sets the maximum Java heap size -xss <size> Sets the Java thread stack size -xprof Outputs CPU configuration file data -xFuture Enable the most stringent checks, Expected future defaults -xRS reduces Java/VM use of OS signals (see documentation) -xCheck :jni Performs additional checks on JNI functions -xshare :off Does not attempt to use shared class data -xshare :auto Use shared class data when possible (default) -xshare :on Requires shared class data to be used, otherwise it will fail. -xshowSettings displays all Settings and continues. -xshowSettings :all Displays all Settings and continues. -xshowSettings: VM Displays all Settings related to the VM and continues Displays all property Settings and continues. -xshowSettings :locale Displays all locale-related Settings and continues. The -x option is non-standard and subject to change without notice.Copy the code

How do you know that the JVM is using mixed mode by default?

Similarly, using the Java -version command, you can see the word mixed mode, which indicates that the current system is in mixed mode

4.1.3. Type 3: -xx parameter option

Boolean type format

-xx :+<option> Enables the option attribute. -xx :-<option> Disables the option attributeCopy the code

Non-boolean type format

-xx :<option>=<number> Sets the option value. The unit can be k/ k/ m/ m/ g/ g-xx :<option>=<string> Sets the option character valueCopy the code

4.2. Add JVM parameter options

You don’t need to specify Configurations in Eclipse and IDEA. You can configure them in VM Options in Run Configurations

Run the jar package

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

Tomcat runs the WAR package

#Catalina. sh was added in Linux
JAVA_OPTS="-Xms512M -Xmx1024M"
#Catalina. bat was added in Windows
set "JAVA_OPTS=-Xms512M -Xmx1024M"
Copy the code

Program in operation

#Sets Boolean type parameters
jinfo -flag [+|-]<name> <pid>
#Sets non-Boolean type parameters
jinfo -flag <name>=<value> <pid>
Copy the code

4.3. Common JVM parameter options

4.3.1. Print XX options and values for Settings

-xx :+PrintCommandLineFlags The XX option that the JVM defaults to when the program runs or that the user manually sets. -xx :+PrintFlagsInitial Prints the default values for all XX options. -xx :+PrintFlagsFinal Prints actual values for all XX options -xx :+PrintVMOptions Prints parameters for the JVMCopy the code

4.3.2. Memory size Settings of heap, stack, method area, etc

#The stack-xss128k <==> -xx :ThreadStackSize=128k sets the ThreadStackSize to 128k
#The heap-xMS2048m <==> -xx :InitialHeapSize=2048m Set the initial HEAP memory of JVM to 2048m -XMx2048m <==> -xx :MaxHeapSize=2048m Set the maximum heap memory of JVM to 2048m-xmn2g <==> -xx :NewSize= 2G-XX :MaxNewSize= 2G Set the size of young generation to 2G-XX :SurvivorRatio=8 Set the ratio of Eden area to Survivor area. The default value is 8-xx :NewRatio=2 Sets the ratio of the old generation to the young generation. The default value is 2-xx :+UseAdaptiveSizePolicy Sets the size ratio to be adaptive. The default open - XX: PretenureSizeThreadshold = 1024 set is greater than the threshold value of object directly in old age, -xx :MaxTenuringThreshold=15 Sets the age limit for the new generation to advance to the old generation. Default 15-XX :TargetSurvivorRatio Sets the expected ratio of Survivor zone space after MinorGC ends
#Methods area-xx :MetaspaceSize / -xx :PermSize=256m The initial value of the MetaspaceSize/permanent generation is 256m. -xx :MaxMetaspaceSize / -xx :MaxPermSize=256m The maximum value of the MetaspaceSize/permanent generation is 256m - XX: + UseCompressedOops use compression object - XX: + UseCompressedClassPointers use compressed class pointer - XX: CompressedClassSpaceSize set Klass Metaspace size, The default 1 g
#Direct memory-xx :MaxDirectMemorySize Specifies the DirectMemory capacity. The default value is equal to the maximum Java heap sizeCopy the code

4.3.3. OutOfMemory related options

-xx :+HeapDumpOnOutMemoryError Heap dump files are generated when the memory is OOM. The two are mutually exclusive. -xx :+HeapDumpBeforeFullGC Heap dump files are generated when FullGC is FullGC. -xx :HeapDumpPath=<path> Specifies the path where the heap dump file is stored. By default, the current directory is. -xx :OnOutOfMemoryError=<path> Specifies the path of the feasible program or script that will be executed when OOM occursCopy the code

4.3.4. Garbage collector related options

The first step is to understand how garbage collectors work together

  • The red dotted line indicates that it was deprecated at JDK8 and deleted at JDK9
  • The green dotted line indicates that it was deprecated at JDK14
  • The green dotted box indicates that it was deprecated at JDK9 and removed at JDK14

#Serial collector-xx :+UseSerialGC Uses SerialGC for younger generations and Serial Old GC for older generations#ParNew collector-xx :+UseParNewGC Young generation using ParNewGC -xx :ParallelGCThreads Sets the number of threads for the young generation parallel collector. In general, it is best to match the number of cpus to avoid too many threads affecting garbage collection performance.Copy the code

P a r a l l e l G C T h r e a d s = { C P U _ C o u n t ( C P U _ C o u n t < = 8 ) 3 + ( 5 C P U _ C o u n t / 8 ) ( C P U _ C o u n t > 8 ) ParallelGCThreads = \begin{cases} CPU\_Count & \text (CPU\_Count <= 8) \\ 3 + (5 * CPU_Count / 8) \\ text (CPU\_Count >) 8) \end{cases}
#The Parallel collector-xx :+UseParallelGC insane -xx :+UseParallelOldGC Insane OldGC, Cross-activation -xx :ParallelGCThreads -xx :MaxGCPauseMillis Sets the maximum garbage collector pause time (that is, the time of STW) in milliseconds. To keep the pause time within MaxGCPauseMills as much as possible, the collector adjusts the Java heap size or some other parameter as it works. For users, the shorter the pause, the better the experience; But the server side focuses on high concurrency, overall throughput. So the server side is suitable for Parallel control. Use this parameter with caution. -xx :GCTimeRatio ratio of the garbage collection time to the total time (1 / (N+1)), which measures the throughput. The value range is 0,100. The default value is 99. Is somewhat contradictory to the previous -xx: MaxGCPauseMillis parameter. The longer the pause time, the Radio parameters tend to exceed the set ratio. -xx :+UseAdaptiveSizePolicy Sets the Parallel Scavenge avenge has an adaptive adjustment policy. In this mode, parameters such as the size of the young generation, the ratio of Eden to Survivor, and the age of objects promoted to the old generation are automatically adjusted to achieve a balance between heap size, throughput, and pause time. In cases where manual tuning is difficult, you can use this adaptive approach to specify only the maximum heap of the virtual machine, the throughput of the target (GCTimeRatio), and the pause time (MaxGCPauseMills), and let the virtual machine do the tuning itself.Copy the code
#CMS collector-xx :+UseConcMarkSweepGC The young generation uses the CMS GC. After this parameter is enabled, -xx: +UseParNewGC is automatically enabled. Namely: ParNew (Young) + CMS (Old) + Serial combination of Old - XX: CMSInitiatingOccupanyFraction setting threshold of heap memory usage, once reached the threshold, began to recycle. The default value for JDK5 and earlier versions is 68, and the default value for DK6 and later versions is 92%. If the memory growth is slow, you can set a larger threshold. A larger threshold can effectively reduce the triggering frequency of the CMS, and reduce the number of old reclaim times, which can significantly improve application performance. Conversely, if your application's memory usage is growing rapidly, you should lower this threshold to avoid triggering the old serial collector too often. Therefore, this option can effectively reduce the number of Fu1l GC executions. - XX: whether + UseCMSInitiatingOccupancyOnly dynamic adjustable, CMS has been pushing to set the value of the startup - XX CMSInitiatingOccupancyFraction: + UseCMSCompactAtFullCollection is used to specify the execution of the Full GC to compress the memory space after finishing In order to avoid memory fragments. The problem, however, is that the pause times become longer because the memory compacting process cannot be executed concurrently. - XX: CMSFullGCsBeforeCompaction set after how many times perform Full GC to compress the memory space. -xx :ParallelCMSThreads Sets the number of CMS threads. The default number of threads started by CMS is (ParallelGCThreads+3)/4. ParallelGCThreads is the number of threads for the young generation of parallel collectors. When CPU resources are tight, application performance can be very poor during the garbage collection phase due to the impact of CMS collector threads. -xx :ConcGCThreads Sets the number of concurrent garbage collection threads, By default this value is calculated based on ParallelGCThreads -xx :+CMSScavengeBeforeRemark forces hotspot to do a minor GC before CMS remark. -xx :+CMSClassUnloadingEnable If any, Enable recycling Perm area (before JDK8) - XX: + CMSParallelInitialEnabled for open CMS initial - mark phase using multi-threaded manner Used to increase the speed of tag, -xx :+ cmsparallelEnabled The REMARKS in the CMS remark phase. The default open - XX: + ExplicitGCInvokesConcurrent - XX: + ExplicitGCInvokesConcurrentAndUnloadsClasses The user specifies that the hotspot virtual uses the CMS cycle -xx :+CMSPrecleaningEnabled when executing System.gc() to specify whether the CMS needs to do the Precleaning phaseCopy the code
#G1 collector-xx :+UseG1GC manually specifies the use of the G1 collector to perform memory reclamation tasks. -xx :G1HeapRegionSize Sets the size of each Region. The value is a power of 2, ranging from 1MB to 32MB, and the goal is to partition about 2048 regions based on the minimum Java heap size. The default is 1/2000 of the heap. -xx :MaxGCPauseMillis sets the maximum GC pause time metric that the JVM will try to achieve, but is not guaranteed to achieve. The default is 200ms -xx :ParallelGCThread Sets the value for the number of GC threads at STW. Maximum set to 8-XX :ConcGCThreads Sets the number of concurrent threads to mark. Set n to about 1/4 of the number of parallel garbage collection threads (ParallelGCThreads). - XX: InitiatingHeapOccupancyPercent set trigger a concurrent GC cycle Java heap usage rate threshold value. If this value is exceeded, GC is triggered. The default value is 45. -xx :G1NewSizePercent Minimum percentage of the entire heap memory occupied by the new generation (default 5%) -xx :G1MaxNewSizePercent Maximum percentage of the entire heap memory occupied by the new generation (default 60%) -xx :G1ReservePercent=10 Preserve memory areas to prevent overflow of to space (the to area in Survivor)Copy the code

How do I choose a garbage collector?

  • Prioritize letting the JVM adapt to the size of the heap
  • Serial collector: memory less than 100M; Single – core, single – machine program, and no pause time requirements
  • Parallel collector: multi-CPU, high throughput, allows pauses of more than 1 second
  • Concurrent collector: multiple cpus, pursuit of low pause times, fast response (e.g., delay of no more than 1 second for Internet applications)
  • The G1 is officially recommended for high performance. The current Internet projects are basically using G1

Special note:

  • There is no single best collector, and there is no universal collector
  • Tuning is always for specific scenarios, specific needs, and there is no one-size-fits-all collector

4.3.5. GC log related options

-xx :+PrintGC <==> -verbose:gc prints brief log information. -xx :+PrintGCDetails Prints detailed log information. -xx :+PrintGCTimeStamps Prints the time when gc occurs. -xx :+PrintGCDetails: -xx :+PrintGCDateStamps: -xx :+PrintGCDetails: -xx :+PrintHeapAtGC: -xx :+PrintHeapAtGC Xloggc:<file> output GC to the file in the specified pathCopy the code

- XX: + TraceClassLoading monitor class load - XX: + PrintGCApplicationStoppedTime print when the GC thread pause time - XX: + PrintGCApplicationConcurrentTime Print garbage collection before the execution time of the application without interrupting - XX: + recycle PrintReferenceGC printing: how many different reference types of references - XX: + PrintTenuringDistribution Prints the age distribution of Survivor objects currently used by the JVM after each MinorGC. -xx :+UseGCLogFileRotation Enables automatic dump of GC log files. -xx :NumberOfGCLogFiles=1 Sets the number of cycles for GC log files -xx :GCLogFileSize=1M Sets the size of the GC log fileCopy the code

4.3.6. Other Parameters

-xx :+DisableExplicitGC disables hotspot to execute system.gc (), Disabled by default - XX: ReservedCodeCacheSize = < n > | | m k [g], - XX: InitialCodeCacheSize = < n > | | m k [g] specifies the size of the code cache - XX: + UseCodeCacheFlushing Discard some of the compiled code, Avoid switching to interpreted only when the code cache is full -xx :+DoEscapeAnalysis turns on escape analysis -xx :+UseBiasedLocking turns on biased locking -xx :+UseLargePages turns on large pages -xx :+PrintTLAB Prints the usage of TLAB. -xx :TLABSize Sets the TLAB sizeCopy the code

4.4. Get JVM parameters through 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 running Java virtual machines to be monitored and managed locally or remotely. The ManagementFactory class is more commonly used, and the Runtime class can obtain memory, CPU cores and other related data. Using these apis, you can monitor the heap memory usage of the application server and set thresholds for alarm and other processing.

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("= = = = = = = = = = = = = = = = = = = = = = = get related system state by Java = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
        System.out.println("Current heap memory size totalMemory" + (int) Runtime.getRuntime().totalMemory() / 1024 / 1024 + "m");// The 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 available total heap memory maxMemory" + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "m");// Maximum available total heap memory size}}Copy the code