JVM runtime Parameters

The parameter types

Official website Parameters

– Standard parameter options

  • The characteristics of
    • Relatively stable, the subsequent version will not change
    • Begin with –
    • Run Java or Java-help to see all the standard options

  • Hotspot JVM has two modes, passed separately-serverand-clientMode setting
    • On 32-bit Windows systems, Client type JVMS are used by default. To use Server mode, the machine must have 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
    • Server-only JVMS on 64-bit machines, suitable for applications requiring large memory, use parallel garbage collectors by default

The official website of the Server and client

-x parameter option

  • The characteristics of
    • Nonstandardized parameter
    • The function is relatively stable. But officials say future releases may change
    • Begin with – X
    • Run the Java -x command to see all the X options

  • Options related to the JVM’s JIT compilation mode
    • -XintWith JIT disabled, all bytecode is interpreted and executed, which is the slowest mode
    • -Xcomp: All bytecode is compiled into local code the first time it is used and then executed
    • -XmixedMixed mode, the default mode that allows the JIT to selectively compile and save some code depending on how the program is running
  • About memory Settings options
    • -Xms<size>: Sets the initial Java heap size, equivalent to-XX:InitialHeapsize
    • -Xmx<size>: Sets the maximum Java heap size, equivalent to-XX:MaxHeapsize
    • -Xss<size>: Sets the Java thread stack size, equivalent to-XX:ThreadStackSize

-xx Parameter option

  • The characteristics of
    • Nonstandardized parameter
    • Such options are experimental and unstable
    • Begin with – XX
    • Purpose: Used to develop and debug the JVM
  • classification
    • Boolean type format
      • -xx :+
      • -xx :-
      • Note: Because some commands are on by default, you can use – off
    • Non-boolean type format (key-value type)
      • Subtype 1: Numeric format -xx :
      • Subtype 2: Non-numeric format -xx :

        =

  • -XX:+PrintFlagsFinal
    • Prints the names and default values of all parameters
    • Diagnostic and Experimental parameters are not included by default
    • Can cooperate with-XX:+UnlockDiagnosticVMOptionsand-XX:UnlockExperimentalVMOptionsuse

Adding parameters

The eclipse add

The idea of adding

Run the jar package

java -Xms50m -Xmx50m -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -jar demo.jar

Tomcat runs the WAR package

  • In Linux, you can add the following information in tomcat/bin/catalina.sh:JAVA_OPTS = "-- Xms512M Xm x 1024 m"
  • Add the following information to catalina.bat in Windows:set "JAVA_OPTS=-Xms512M -Xmx1024M"

Set during program running

  • jinfo -flag <name> =<value> <pid>: Sets non-boolean type parameters
  • jinfo -flag [+/-]<name> <pid>: Sets Boolean type parameters

Parameters marked manageable can only be modified with jinfo

View the available parameters

java -XX:+PrintFlagsFinal -version | grep manageable

Common JVM parameters

Print Settings related to parameters

  • -XX:+PrintCommandLineFlags: allows you to print XX options manually set by the user or automatically set by the JVM before the program runs
  • -XX:+PrintFlagsInitial: prints the default values of all XX options
  • -XX:+PrintFlagsFinal: prints the value of the XX option in effect when the program is run
  • -XX:+PrintVMOptions: Prints parameters for the JVM

The stack

  • -Xss128k: Set the stack size of each thread to 128K; Is equivalent to-XX:ThreadStackSize=128k

The heap

  • -Xms3550m: equivalent to the-XX:InitialHeapSize, set the JVM initial heap memory to 3550M
  • -Xmx3550m: equivalent to the-XX:MaxHeapSize, set the maximum heap memory of the JVM to 355OM
  • -Xmn2g: Set the size of the young generation to 2G (3/8 of the total heap size is recommended)
  • -XX:NewSize=1024m: Sets the initial value of the young generation to 1024 MB
  • -XX:MaxNewSize=1024m: Sets the maximum value of the young generation to 1024 MB
  • -XX:SurvivorRatio=8 : Sets the ratio of Eden to Survivor in the young generation. The default value is 8
  • -XX:+UseAdaptiveSizePolicy: This function is enabled by default. The area size ratio is automatically selected
    • JVM defaults SurvivorRatio=8, but the ratio of Eden to S0 and S1 is 6:1:1 because this parameter is enabled, as long as the application explicitly assigns SurvivorRatio=8, it is 8:1:1 regardless of whether this parameter is enabled.)
  • -XX:NewRatio=2: Sets the ratio of the old generation to the young generation (including 1 Eden and 2 Survivor zones)
  • -XX:PretenureSizeThreadshold=1024: sets objects larger than this threshold to be allocated directly in the old age, in bytes; Only valid for Serial, ParNew collectors
  • -XX:MaxTenuringThreshold=15The default value is 15. After each MinorGC of the new generation, the age of the surviving object is +1. When the age of the object is older than this value, the object enters the old age
  • -XX:+PrintTenuringDistribution: lets the JVM print out the age distribution of currently used Survivor objects after each MinorGC
  • -XX:TargetSurvivorRatio: indicates the expected percentage of space occupied in a Survivor zone after MinorGc ends

Methods area

  • The permanent generation
    • -XXXPermSize=256m: Sets the initial value of the permanent generation to 256M
    • -XX:MaxPermSize=256m: Sets the maximum permanent generation to 256 MB
  • dimension
    • -XX:MetaspaceSize: Initial space size
    • -XX:MaxMetaspaceSize: Maximum space, no limit by default
    • -XX:+UseCompressedOops: Compacts the object pointer
    • -XX:+UseCompressedClassPointers: Compressed class pointer
    • -XX:CompressedClassSpacesize: Set the Klass Metaspace size, default 1 gb

Direct memory

  • -XX:MaxDirectMemorySize: Specifies the DirectMemory capacity. If this is not specified, it is the same as the maximum Java heap size by default

OOM related

  • -XX:+HeapDumpOnOutOfMemoryError: indicates that the memory Heap is dumped to a file for subsequent analysis when OOM is displayed
  • -XX:+HeapDumpBeforeFullGC: indicates that the Heap dump file is generated before FullGC occurs
  • -XX:HeapDumpPath= d:\heapdump.hprof: Specifies that the heapdump file is stored in heapdump.hprof on disk D. The file name increases by 1, for example, heapdump.hprof.2
  • -XX:OnOutOfMemoryError: Specifies the path to a viable program or script that will be executed when OOM occurs

Description:

The following uses server. jar deployed in the /opt/Server directory in Linux as an example to describe how to o&M OnOutOfMemoryError

  1. Add JVM parameters to the run.sh startup script, execute the script when OOM occurs:

-XX:OnOutOfMemoryError=/opt/Server/restart.sh

  1. Restart. Sh scripts
  • Linux environment:
#! /bin/bash pid=$(ps -ef|grep Server.jar|awk'{if($8=="java") {print $2}}')
kil1 -9$pid cd /opt/Server/; sh run.shCopy the code
  • Windows environment:
echo off
wmic process where Name= 'java.exe' delete
cd D:\Server
start run.bat
Copy the code

Garbage collector related

  • -XX:+PrintCommandLineFlags: View command-line parameters (including the garbage collector used)
  • Jinfo-flag < Related garbage collector parameters > < process ID>: Command line command to query usage
  • Jdk8 default garbage collector:-XX:+UseParallelGCTo be insane + insane
  • Jdk11 default garbage collector:-XX:+UseG1GC

Serial collector

  • The Serial collector is the default new generation garbage collector in Client mode in HotSpot. Serial Old is the default old garbage collector running in Client mode.
  • -XX:+UseSerialGC: Specifies that both young and old generations use serial collectors. This is equivalent to replacing Serial GC for freshmen and Serial old GC for seniors. For maximum single-thread collection efficiency.

ParNew collector

  • -XX:+UseParNewGC: Manually specifies the use of the ParNew collector to perform memory reclamation tasks. It means that the younger generation uses the parallel collector without affecting the older generation.
  • -XX:ParallelGCThreads=N : limits the number of threads. By default, the number of threads is the same as the CPU data.

The Parallel collector

  • -XX:+UseParallelGC: Manually specifies that the young generation uses the Paralle1 parallel collector to perform memory reclamation tasks.
  • -XX:+UseParallelOldGC: Manually specify that older generations are using parallel collection collectors.
    • It applies to the new generation and the old age respectively. Jdk8 is enabled by default.
    • One of the above two parameters is enabled by default, and the other is enabled as well.(Mutual activation)
  • -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.
    • By default, when the number of cpus is less than eight, ParallelGCThreads is equal to the number of cpus.
    • When there are more than eight cpus, ParallelGCThreads is equal to 3+[5*CPU_Count]/8].
  • -XX:MaxGCPauseMillis: Sets the maximum garbage collector pause time (that is, the time of STw). The units are 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 on the server side, we focus on high concurrency, overall throughput. So the server side is suitable for Parallel control.
    • Use this parameter with caution.
  • -XX:GCTimeRatio: Ratio of garbage collection time to total time (= 1 / (N + 1)). Used to measure throughput size.
    • The value ranges from 0 to 100. The default value is 99, which means the garbage collection time is less than 1%.
    • Is somewhat contradictory to the previous -xx :MaxGCPauseNillis parameter. The longer the pause time, the Radio parameters tend to exceed the set ratio.
  • -XX:+UseAdaptiveSizePolicyThe Parallel Avenge collector has an adaptive adjustment strategy
    • 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 adjusted automatically to reach 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.

CMS collector

  • -XX:+UseConcMarkSweepGC: Manually specifies the use of the CMS collector to perform memory reclamation tasks.
    • After this parameter is enabled, -xx :+UseParNewGC is automatically enabled. ParNew(Young)+CMS(Old)+ Serial Old.
  • -XX:CMSInitiatingOccupancyFraction: Sets a threshold for heap memory usage. Once this threshold is reached, collection begins.
    • The default value for JDK5 and previous versions is 68, which means that a CMS collection is performed when the space usage of the older generation reaches 68%.
    • The default value for JDK6 or later 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 times Ful1 GC is executed.
  • -XX:+UseCMSCompactAtFullCollection: specifies that the memory space should be compressed after Full GC to avoid memory fragmentation. The problem, however, is that the pause times become longer because the memory compacting process cannot be executed concurrently.
  • -XX:CMSFullGCsBeforeCompaction: Sets the number of Full GC runs before the memory space is compressed.
  • -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 calculated based on ParallelGCThreads by default
  • -XX:+UseCMSInitiatingOccupancyOnlyWhether dynamic adjustable, press with the parameters can make the CMS has been CMSInitiatingOccupancyFraction set the value of the startup
  • -XX:+CMSScavengeBeforeRemark: Forces the hotspot VIRTUAL machine to do a Minor GC before the CMS remark phase to speed up the remark phase
  • -XX:+CMSClassUnloadingEnable: Enable reclaim Perm zone (before JDK8), if any
  • -XX:+CNSParallelInitialEnabled: used to enable the CMS initial-mark phase. Multi-threaded marking is used to improve the marking speed. It is enabled by default in Java8
  • -XX:+CMSParallelRemarkEnabled: Enable THE CMS remark phase. Multi-threaded marking is enabled by default
  • -XX:+ExplicitGCInvokesConcurrent-XX:+ExplicitGCInvokesConcurrentAndUnloadsclassesThe user specifies that the hotspot virtual uses CMS cycles when system.gc () is executed;
  • -XX:+CMSPrecleaningEnabled: Specifies whether the CMS needs to do the Pre cleaning phase

Version Description:

  • New JDK9 feature :CMS marked as Deprecate (JEP291)
    • If parameters are used for the HotSpot VIRTUAL machine of JDK9 and later-XX:+UseConcMarkSweepGCTo enable the CMS collector, the user will receive a warning that the CMS will be deprecated in the future.
  • New features for JDK14: Remove CMS garbage collector (JEP363)
    • Remove the CMS garbage collector if used in JDK14-XX:+UseConcMarkSweepGCThe JVM does not return an error, just a warning message, but no exit. The JVM automatically falls back and starts the JVM in the default GC mode

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 and ranges from 1MB to 32NB, with the goal of partitioning about 2048 regions based on the minimum Java heap size. The default is 1/2000 of the heap.
  • -XX:MaxGCPauseMillis: Sets the desired maximum GC pause time metric (which the JVM tries to achieve, but is not guaranteed to achieve). The default value is 200ms
  • -XX:ParallelGCThread: Sets the value of the number of GC threads at STW. The maximum value is 8
  • -XX:ConcGCThreads: Sets the number of threads to mark concurrently. Set n to about 1/4 of the number of parallel garbage collection threads (ParallelGCThreads).
  • -XX:InitiatingHeapOccupancyPercent: Sets the Java heap usage threshold that triggers concurrent GC cycles. If this value is exceeded, GC is triggered. The default value is 45.
  • -XX:G1NewSizePercent,-XX:G1MaxNewSizePercent: Minimum percentage (default 5%), maximum percentage (default 60%) of total heap memory occupied by the new generation
  • -XX:G1ReservePercent=10: Reserves the memory area to prevent overflow of the TO area in Survivor

Note: The G1 collector mainly involves Mixed GC, which reclaims young and part of old GC.

G1 About Mixed GC tuning

  • -XX:InitiatingHeapOccupancyPercent: Sets the percentage of heap usage (0 to 100) to trigger global concurrent marking (45% by default) when this number is reached. A value of 0 indicates intermittent global concurrency marking.
  • -XX:G1MixedGCLiveThresholdPercent: Sets the proportion of objects reclaimed from the region in the old region. The default value is 85%. A Mixed GC will only reclaim a region with this percentage of living objects in the old region.
  • -XX:G1HeapWastePercent: After global Concurrent marking, you can know how much space is to be reclaimed for all partitions. After each young GC and before the Mixed GC occurs again, the garbage percentage is checked to see if this parameter is reached. Mixed GC will occur next time.
  • -XX:G1MixedGCCountTarget: The maximum number of Mixed GC executions after one Global Concurrent marking. The default is 8.
  • -XX:G1OldCSetRegionThresholdPercent: Sets the upper limit on the number of Old regions to collect in a Mixed GC collection cycle. The default value is 10% of the Java heap

With G1, it is not recommended to set the heap size and scale size. Let the JVM automatically adapt and set G1 parameters.

How do I choose a garbage collector

  • Prioritizing the heap size allows the JVM to adapt.
  • If the memory is less than 100M. Using a serial collector
  • If it is a single-core, single-machine program, and no pause time requirements, serial collector
  • If it is multi-CPU, requires high throughput, and allows pause times of more than 1 second, choose parallelism or the JVM’s choice
  • If you have multiple cpus and are looking for low pause times that require fast responses (such as a delay of no more than 1 second, as in Internet applications), use a concurrent collector. The G1 is officially recommended for high performance. The current Internet projects are basically using G1.
  • Scenario-specific, analysis-specific

GC log correlation

  • -verbose:gc: Outputs GC log information, which is output to standard output by default
  • -XX:+PrintGC: equivalent to -verbose:gc enables simplified GC logs
  • -XX:+PrintGCDetails: Prints a detailed memory collection log when garbage collection occurs and displays the current memory allocation when the process exits
  • -XX:+PrintGCTimeStamps: Prints the timestamp when GC occurs
  • -XX:+PrintGCDateStamps: Outputs the timestamp when GC occurs (in the form of a date, e.g. 2021-10-04T21:53:59.234+0800)
  • -XX:+PrintHeapAtGC: The heap information is printed before and after each GC
  • -Xloggc:<file>: Writes GC logs to a file instead of printing them to standard output
  • -XX:+TraceClassLoading: Monitors class loading
  • -XX:+PrintGCApplicationStoppedTime: Prints the pause time of the thread during GC
  • -XX:+PrintGCApplicationConcurrentTime: Prints the uninterrupted execution time of the application before garbage collection
  • -XX:+PrintReferenceGC: Records how many references of different reference types are recycled
  • -XX:+PrintTenuringDistribution: lets the JVM print out the age distribution of currently used Survivor objects after each MinorGC
  • -XX:+UseGCLogFileRotation: Enables automatic dump of GC log files
  • -XX:NumberOfGClogFiles=1: Number of cycles for GC log files
  • -XX:GCLogFileSize=1M: Controls the size of the GC log file

The other parameters

  • -XX:+DisableExplicitGC : Disallows hotspot to execute system.gc () by default
  • -XX:ReservedCodeCacheSize=<n>[g|m|k],-XX:InitialCodeCacheSize=<n>[g|m|k]: Specifies the size of the compiled code cache
  • -XX:+UseCodeCacheFlushing: Use this parameter to force the JVM to discard some compiled code, avoiding the tendency for the JVM to switch to interprelator-only when the code cache is full
  • -XX:+DoEscapeAnalysis: Enables escape analysis
  • -XX:+UseBiasedLocking: Enable bias lock
  • -XX:+UseLargePages: Enables the use of large pages
  • -XX:+UseTLAB: Use TLAB, enabled by default
  • -XX:+PrintTLAB: Prints TLAB usage
  • -XX:TLABSize: Sets the TLAB size

Java code gets JVM parameters

Java provides the java.lang.management package for monitoring and managing Java Virtual machines and other components in the AVA runtime, which allows running Java virtual machines to be monitored and managed locally and remotely. The ManagementFactory class is quite commonly used. In addition, the Runtime class can also fetch some memory CPU cores and other related data.

These apis allow us to monitor the heap memory usage of our application servers, set thresholds for alarms, and so on.

public static void main(String[] args) {
    System.out.println("= = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =");
    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("MaxMemory in the most usable total heap" + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "m");// Maximum available total heap memory size

}
Copy the code

In-depth understanding of the JVM family

  • 1. In-depth understanding of the JVM (I) – Introduction and architecture
  • 2. In-depth understanding of the JVM II – 1 classloader subsystem
  • 3. In-depth understanding of THE JVM (III) – Runtime data area (virtual machine stack)
  • 4. In-depth understanding of THE JVM (IV) – runtime data area (program counter + local method stack)
  • 5. In-depth understanding of THE JVM (V) – Runtime data area (heap)
  • 6. In-depth understanding of THE JVM (VI) – Runtime data area (methods area)
  • 7. In-depth understanding of the JVM (vii) – execution engine (interpreter and JIT compiler)
  • 8. An in-depth understanding of the JVM (8) – string constant pool
  • 9. In-depth understanding of JVM (IX) – object instantiation and memory layout
  • 10. In-depth understanding of JVM (x -) – bytecode level profiler execution
  • 11. In-depth understanding of concepts related to JVM (xi) garbage collection
  • 12. In-depth understanding of JVM (xii) – garbage collection algorithms
  • 13. Take a closer look at the JVM (13) – garbage collector
  • 14. Dig deep into the JVM (XIV) one – object distribution map
  • 15. In-depth understanding of the JVM (XV) -class file structure
  • 16. An in-depth understanding of the JVM (XVI) one bytecode instruction set
  • 17. In-depth understanding of the JVM (17) -class lifecycle details
  • 18. Further understanding of the JVM (18) — more about class loaders
  • 19. In-depth Understanding of the JVM (19) – JVM Monitoring and Diagnostics Tools (command line)
  • In-depth understanding of the JVM (20) — JVM Monitoring and Diagnostics Tools (GUI)