Note source: Silicon Valley JVM full tutorial, one million playback, the whole network peak (Song Hongkang detailed Java virtual machine)
Synchronous update: https://gitee.com/vectorx/NOT…
https://codechina.csdn.net/qq…
https://github.com/uxiahnan/N…
[TOC]
4. JVM runtime parameters
4.1. JVM parameter options
Website address: https://docs.oracle.com/javase/8/docs/technotes/tools/windows/java.html
4.1.1. Type 1: Standard parameter options
> Java -help: Java [-options] class [args... Java [-options] -jar JarFile [args...] (Execute the JAR file) The options include: -D32 uses 32-bit data model (if available) -D64 uses 64-bit data model (if available) -Server selects "Server" VM default VM is server. -cp < directory and zip/jar file in the class search path > -classpath < directory and zip/jar file for class search path >; Separated directories, lists of JAR files and ZIP files, for searching for 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>[=< option >] Load native agent libraries by full pathname -javaAgent :<jarpath>[=< option >] Loads Java programming language agent, see java.lang.instrument - Splash :<imagepath> displays startup screen details using the specified image, Please refer to http://www.oracle.com/technetwork/java/javase/documentation/index.html.
Server and Client modes
The Hotspot JVM has two modes, Server and Client, which are set through -Server and -Client modes, respectively
- On 32-bit systems, the default JVM is the Client type. To use Server mode, the machine is configured with at least two or more CPUs and at least 2GB of physical memory. The Client pattern is suitable for desktop applications with low memory requirements and uses the Serial Serial Garbage Collector 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: https://docs.oracle.com/javase/8/docs/technotes/guides/vm/server-class.html
How do you know which mode is being used by default?
With the java-version command: you can see the words Server VM, which means the current system is in Server mode
> Java - Version Java 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)
4.1.2. Type 2: -X parameter option
> java-x-xMixed mode execution (default) -Xint only explained mode execution -Xbootclasspath:< with; Separated directories and zip/jar files > set the search path to boot classes and resources - xBootClasspath /a:< with; The delimited directory and zip/jar file > are attached at the end of the bootclasspath -Xbootclasspath/p:< with; Delimited directory and zip/jar file> before boot classpath -Xdiag displays additional diagnostic messages -Xnoclassgc disables class garbage collection -Xincgc enables incremental garbage collection -Xloggc:<file> records GC status in file (with timestamp) -xbatch disables background compilation -xms <size> sets initial Java heap size -xmx <size> sets maximum Java heap size -xss <size> sets Java thread stack size -xprof outputs CPU profile data -xfuture Enable the most stringent checks, Expected future defaults - XRS reduces Java/VM use of operating system signals (see documentation) - XCheck: JNI performs additional checks on JNI functions - XShare: OFF Do not attempt to use shared class data - XShare: AUTO Use shared class data when possible (default) -xshare :on requires shared class data or it will fail. -XShowSettings displays all Settings and continues -XShowSettings: All displays all Settings and continues -XShowSettings: VM displays all VM related Settings and continues -XShowSettings: Properties Display all property Settings and continue -XShowSettings: Locale displays all local-related Settings and continue -X option is non-standard and is subject to change without notice.
How do you know that the JVM is in mixed mode by default?
Similarly, with 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 option attributes -XX:-<option> Enables option attributes
Non-boolean type format
-xx :<option>=<number> -xx :<option>=<string> -xx :<option>=<number> -xx :<option>=< option>
4.2. Add JVM parameter options
If you want to configure Eclipse and Idea, you can configure them in Run Configurations
Run the jar package
java -Xms100m -Xmx100m -XX:+PrintGCDetails -XX:+PrintGCDateStamps -XX:+PrintGCTimeStamps -jar demo.jar
Tomcat runs the WAR package
Mysql > set JAVA_OPTS= -xms512m-xmx1024m mysql > set JAVA_OPTS= -xms512m-xmx1024m mysql > set JAVA_OPTS= -xms512m-xmx1024m
Program running
# set the Boolean type parameter jinfo - flag [+ | -] < name > < pid > # set the Boolean type parameter jinfo - flag < name > = < value > < pid >
4.3. Common JVM parameter options
4.3.1. Print the XX option and value of the setting
-XX:+PrintCommandLineFlags The program runs with XX options set by the JVM default or manually by the user -XX:+PrintFlagsInitial prints the default values for all XX options -XX:+PrintFlagsFinal Prints the actual values of all XX options -XX:+PrintVMOptions prints the JVM's parameters
4.3.2. Set the memory size of heap, stack, method area, etc
# stack -xss128k <== >-XX :ThreadStackSize=128k # heap -xms2048m <== >-XX :InitialHeapSize=2048m # stack -xms2048m <== >-XX :InitialHeapSize=2048m Set the JVM's initial heap memory to 2048m -xmx2048m <== >-xx: maxHeapSize =2048m -xmn2g <== >-xx: newSize = 2g-xx: maxNewSize =2g -xmx2048m <== >-xx: newSize =2g -xmn2g: maxNewSize =2g -XX:SurvivorRatio=8 sets the ratio between the Eden and Survivor regions. The default is 8-XX :NewRatio=2 sets the ratio between the older generation and the younger generation. The default is 2-XX :+ UseAdaptivesizePolicy sets the size ratio 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 be promoted to the old one, Defaults to 15-XX: targetSurvivorRatio to set the expected percentage of space taken up by Survivor sections after MinorGC # method section -XX:MetaspaceSize / -XX: permSize = 256M Sets the initial value of metasize/permanent to 256M -XX: maxMetaspacesize / -XX: maxpermSize = 256M. Sets the maximum value of metasize/permanent to 256M -XX:+ UseCompresseDoops to use compressed objects - XX: + UseCompressedClassPointers use compressed class pointer - XX: CompressedClassSpaceSize set Klass Metaspace size, Default 1G # DirectMemory -XX:MaxDirectMemorySize specifies DirectMemory capacity, which is equal to the maximum Java heap by default
4.3.3. OutOfMemory related options
-XX:+ HeapDumponOutMemoryError generates a Heap dump when the memory appears OOM and the two are mutual exclusive -XX:+HeapDumpBeforeFullGC generates a Heap dump when the FullGC occurs The two are mutually exclusive -XX:HeapDumpPath=<path> specifies the path to the heap dump, and the default current directory -XX: onOutOfMemoryError =<path> specifies the path to a viable program or script that executes when an OOM occurs
4.3.4. Garbage collector related options
The first thing you need to understand is the collocation of the garbage collectors
- The red dotted line indicates Deprecate in JDK8 and deleted in JDK9
- The dashed green line indicates Deprecate at JDK 14
- The green box indicates that it is deprecated in JDK9 and deleted in JDK14
-XX:+ useSerialGC -XX:+ useSerialGC -XX:+ useSerialGC The young generation uses Parnew GC-XX :ParallelGCThreads to set the number of threads in the young generation's parallel collector. In general, it is best to match the number of CPUs to avoid having 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} $$
-XX:+ UseParallelgc -XX:+ UseParalleloldgc -XX:+ UseParalleloldgc -XX:+ UseParalleloldgc -XX:+ UseParalleloldgc -XX:+ UseParalleloldgc -XX:+ UseParalleloldgc -XX:ParallelGCThreads -XX:MaxGCPauseMillis sets the garbage collector's maximum pause time (that is, STW time) in milliseconds. In order to keep the pause time within maxGCPauseills as much as possible, the collector adjusts the Java heap size or other parameters as it works. For the user, 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. This parameter should be used with caution. -XX: The ratio of GCTimeRatio garbage collection time to the total time (1 / (N+1)), used to measure the size of the throughput range (0,100). The default value is 99, which means the garbage collection time is no more than 1%. There is a certain contradiction with the previous -XX: MAXGCPauseMillis parameter. The longer the pause time, the easier it is for the RADIO parameter to exceed the set ratio. -XX:+ UseAdaptivesizePolicy sets the Parallel Scavenge collector to have 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, this adaptive approach can be used directly, specifying only the maximum heap of the virtual machine, the target throughput (GCTimeRatio), and the pause time (MaxGCPauseMills), and letting the virtual machine do the tuning itself.
-XX:+UseConcMarkSweepGC Young generation uses CMS GC. Enable this parameter automatically turns -XX: +UseParNewGC on. 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 for DK6 and above the default value is 92%. If memory growth is slow, a slightly larger value can be set. A larger threshold can effectively reduce the frequency of CMS triggering, and reducing the number of old collection can significantly improve application performance. On the other hand, if your application memory usage is growing rapidly, you should lower this threshold to avoid frequently triggering older serial collectors. 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. However, since the memory compressing process cannot be executed concurrently, the problem is that the pause time becomes longer. - XX: CMSFullGCsBeforeCompaction set after how many times perform Full GC to compress the memory space. -XX:ParallelCMSThreads sets the number of threads in the CMS. The default number of threads started by CMS is (ParallelGCThreads+3)/4, and ParallelGCThreads is the number of threads in the young generation parallel collector. When CPU resources are tight, application performance can be poor during the garbage collection phase due to the impact of the CMS collector threads. -XX: ConcgcThreads sets the number of concurrent garbage collection threads, By default this value is calculated based on ParallelGCThread -XX:+ CMSSavengeBeForeRemark forces Hotspot to make a minor GC before the CMS remark stage, Used to increase the speed of the remark phase -XX:+CMSClassUnloadingEnable if available, 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:+ cmSparallElRemarkable enabled User opens CMS remark phase and re-marks it in a multi-threaded manner. The default open - XX: + ExplicitGCInvokesConcurrent - XX: + ExplicitGCInvokesConcurrentAndUnloadsClasses These two parameters specify by the user that the Hotspot virtual uses the CMS cycle -XX:+ CMSRecleaningEnableto specify whether the CMS needs to perform the Pres cleaning phase when executing System.gc()
# G1 collector -XX:+UseG1GC manually specifies that the G1 collector is used to perform the memory collection task. -XX:G1HeapRegionSize Sets the size of each Region. The value is a power of 2, with a range of 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 memory. -XX:MaxGCPauseMillis sets the expected maximum GC pause time metric (the JVM will try to achieve this, but it is not guaranteed). The default value is 200ms-XX :ParallelGCThread to set the number of GC threads when STW is set. Set to 8-XX at most: CongcThreads sets the number of threads for concurrent markup. Set n to about 1/4 of the number of ParallelGCThreads. - XX: InitiatingHeapOccupancyPercent set trigger a concurrent GC cycle Java heap usage rate threshold value. Above this value, GC is triggered. The default value is 45. -XX:G1NewSizePercent The maximum percentage of heap memory used by the new generation (default 5%) -XX:G1NewSizePercent The maximum percentage of heap memory used by the new generation (default 60%) -XX:G1ReservePercent=10 Keep memory regions to prevent overflow of to Spaces on vivors
How to select a garbage collector?
- Make the JVM adaptive and adjust the size of the heap first
- Serial collector: memory less than 100M; Single core, single machine program, and no pause time requirements
- Parallel Collector: Multiple CPUs, high throughput, allowing pauses of more than 1 second
- Concurrent collector: multiple CPUs, low pause times, fast response (e.g., latency of no more than 1 second, e.g., Internet applications)
- G1 is officially recommended for high performance. Now the Internet projects, basically all use G1
Special note:
- There is no best collector, and there is no universal collector
- Tuning is always scenario-specific and needs specific, and there is no one-size-fits-all collector
4.3.5. Options related to GC logging
- XX: + PrintGC < = = > - verbose: gc print log information briefly - XX: + PrintGCDetails print log information in detail - XX: + PrintGCTimeStamps print program started to the time of the gc, -xx :+PrintGCDetails uses -xx :+ PrintGCDatestamps to print the timestamp when the GC occurs, and -xx :+PrintGCDetails uses -xx :+ PrintGCDatestamps to print the heap information before and after the GC. Xloggc:<file> output GC guide specified path in the file
- 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 objects in the Survivor that the JVM is currently using after each MinorGC -XX:+ UseGCLOGFileRotation to enable automatic dumping of GC log files -XX: NumberOfGCLOGFiles =1 Sets the number of cycles for GC log files -XX: GclogFileSize =1M Sets GC log file size
4.3.6. Other parameters
-XX:+DisableExplicitGC Disable Hotspot Execution 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 compiled code, Avoid the JVM switching to interpreted-only when the code cache is full -XX:+DoEscapeAnalysis turns on escape analysis -XX:+UseBiasedLocking turns on bias locking -XX:+ useArgepages turns on using large pages -XX:+ PrinttLab Print TLab Usage -XX: TLabSize Sets the TLab size
4.4. Obtaining JVM parameters through Java code
Java provides the java.lang. Management package for monitoring and managing the Java Virtual Machine and other components in the Java runtime, which allows you to monitor and manage a running Java Virtual Machine either locally or remotely. ManagementFactory class is more commonly used, and Runtime class can obtain memory, CPU core count and other related data. Using these APIs, you can monitor the application server’s heap memory usage, set some thresholds for alarm, 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. The out. Println (" = = = = = = = = = = = = = = = = = = = = = = = get related System state by Java = = = = = = = = = = = = = = = = = = = = = = = = = = = = "); System.out.println(" Total Memory "+ (int) Runtime.getRuntime(). TotalMemory () / 1024/1024 +" M "); System.out.println(" Freemory "+ (int) Runtime.getRuntime().Freemory () / 1024/1024 + "m"); Println (" maxMemory "+ runtime.getRuntime ().maxMemory() / 1024/1024 + "m"); // Maximum available total heap size}}