当前位置:网站首页>JVM startup parameters

JVM startup parameters

2021-08-02 13:50:32 wx58f0846670609

java There are three types of startup parameters ;
One is the standard parameter (-), be-all JVM The implementation must realize the function of these parameters , And backward compatibility ;
The second is non-standard parameters (-X), Default jvm Realize the function of these parameters , But there is no guarantee that all jvm The realization is satisfied , And there is no guarantee of backward compatibility ;
The third is Not Stable Parameters (-XX), Each of these parameters jvm The implementation will be different , It may be cancelled at any time in the future , It needs to be used carefully ;
This paper mainly describes the standard parameters , The remaining two parts will be launched one after another ;

The list of standard parameters is as follows :
-client
  Set up jvm Use client Pattern , It is characterized by fast startup speed , But runtime performance and memory management efficiency are not high , Usually used for client applications or PC Application development and debugging .

-server
  Set up jvm send server Pattern , It is characterized by slow start-up speed , But runtime performance and memory management efficiency are very high , Suitable for production environment . In possession of 64 Capable of jdk This mode will be enabled by default , And ignore -client Parameters .

-agentlib:libname[=options]
  Used to mount local lib package ;
  among libname Is the local agent library file name , The default search path is the environment variable PATH In the path ,options Is the parameter passed to the local library at startup , Multiple parameters are separated by commas . stay Windows On the platform jvm Search the local library named libname.dll The file of , stay linux On jvm Search the local library named libname.so The file of , Search path ring Environmental variables are different in different systems , such as Solaries On the default search LD_LIBRARY_PATH.
  such as :-agentlib:hprof
  Used to obtain jvm Operating condition , Include CPU、 Memory 、 Running data of threads, etc , And can be output to the specified file ;windows The search path in is JRE_HOME/bin/hprof.dll.

-agentpath:pathname[=options]
  Load local libraries by full path , No more searching PATH In the path ; Other functions and agentlib identical ; More information to be continued , In the subsequent JVMTI This section will detail .

-classpath classpath
-cp classpath

  inform jvm Search directory name 、jar Document name 、zip Document name , Use a semicolon between ; Separate ; Use -classpath after jvm Will no longer use CLASSPATH Class search path in , If -classpath and CLASSPATH No settings , be jvm Use the current path (.) As a class search path .
 jvm The method and order of searching classes are :Bootstrap,Extension,User.
 Bootstrap The path in is jvm Self contained jar or zip file ,jvm First search for these package files , use System.getProperty("sun.boot.class.path") You can get the search path .
 Extension It's located in JRE_HOME/lib/ext In the catalog jar file ,jvm After searching Bootstrap After that, search the... Under the directory jar file , use System.getProperty("java.ext.dirs") You can get the search path .
 User The search order is the current path .、CLASSPATH、-classpath,jvm Finally, search these directories , use System.getProperty("java.class.path") You can get the search path .

-Dproperty=value
  Set the system property name / It's worth it , Run here jvm The application above is available System.getProperty("property") obtain value Value .
  If value Spaces in , You need to enclose the value in double quotes , Such as -Dname="space string".
  This parameter is usually used to set the value of system level global variables , Such as configuration file path , So that this property can be accessed anywhere in the program .

-enableassertions[:<package name>"..." | :<class name> ]
-ea[:<package name>"..." | :<class name> ]

  The above parameters are used to set jvm Whether to start the assertion mechanism ( from JDK 1.4 Start supporting ), By default jvm Turn off the assertion mechanism .
  use -ea The assertion mechanism can be turned on , No addition <packagename> and classname Run assertions in all packages and classes when , If you want to run only assertions in certain packages or classes , The bag can be Add name or class name to -ea after . For example, to start a package com.wombat.fruitbat The assertion in , Orders available java -ea:com.wombat.fruitbat...<Main Class>.

-disableassertions[:<package name>"..." | :<class ; ]
-da[:<package name>"..." | :<class name> ]

  Used to set jvm Turn off assertion processing ,packagename and classname How to use and -ea identical ,jvm The default is off .
  This parameter is generally used for the same package There are some class Scenarios that do not require assertions , such as com.wombat.fruitbat It needs to be asserted that , however com.wombat.fruitbat.Brickbat This class does not require , Then you can run :
 java -ea:com.wombat.fruitbat...-da:com.wombat.fruitbat.Brickbat <Main Class>.
 
-enablesystemassertions
-esa

  Activate the assertion of the system class .
 
-disablesystemassertions
-dsa

  Close the assertion of the system class .

-jar
  Specified in jar Execute an application in the form of a package .
  To execute an application like this , Must let jar Bag manifest The initial loaded... Is declared in the file Main-class, Of course Main-class There has to be public static void main(String[] args) Method .

-javaagent:jarpath[=options]
  Appoint jvm When starting, enter java Language device agent .
 Jarpath In the document mainfest The document must have Agent-Class attribute . The proxy class must also implement public static public static void premain(String agentArgs, Instrumentation inst) Method ( and main The method is similar to ). When jvm On initialization , Will be called in the order described by the proxy class premain Method ; Specific see java.lang.instrument Description of the package .

-verbose
-verbose:class

  Output jvm Information about loading classes , When jvm It can be used for diagnosis when the report says that no class or class conflict can be found .
-verbose:gc
  Output every time GC About .
-verbose:jni
  Output native Method calls , It is usually used to diagnose jni Call error message .
 
-version
  Output java Version information for , such as jdk edition 、vendor、model.
-version:release
  Appoint class perhaps jar What you need to run jdk Version information ; If the specified version is not found , The system defaults to the one that can be found jdk Version execution ; In general , about jar file , Can be in manifest Specify the required version information in the file , Not on the command line .
 release A single version can be specified in , You can also specify a list , Space separates the middle , And support complex combination , such as :
 -version:"1.5.0_04 1.5*&1.5.1_02+"
  Appoint class perhaps jar need jdk Version is 1.5.0_04 Or is it 1.5 More than... In the series 1.5.1_02 All higher versions .

-showversion
  Output java Version information ( And -version identical ) after , Continue to output java Standard parameter list and its description .
 
-?
-help

  Output java Standard parameter list and its description .

-X
  Output non-standard parameter list and its description .

We often use multiple combinations of these parameters in many cases , For example, we are using JProfiler When tracking and monitoring , Need to be monitored java Add the following configuration... To the startup parameters :
-agentlib:jprofilerti=port=8849  -Xbootclasspath/a:/usr/local/jprofiler5/bin/agent.jar
Two of them -agentlib and -X Parameters ,bootclasspath The details of the parameters will be described in detail in the non-standard parameters .



Nonstandard parameters are also called extended parameters , The list is as follows :
-Xint
  Set up jvm Run in interpretation mode , All bytecodes will be executed directly , Compile code without cost .
 
-Xbatch
  Turn off background code compilation , Force compilation in the foreground , Code execution is not allowed until the compilation is complete ;
  By default ,jvm Compile in the background , If the compilation is not completed , When the foreground runs the code, it runs in interpretation mode .
 
-Xbootclasspath:bootclasspath
  Give Way jvm From the specified path ( Can be semicolon separated directories 、jar、 perhaps zip) Load in bootclass, To replace jdk Of rt.jar; If not necessary , It's not used in general ;
-Xbootclasspath/a:path
  Appends all files in the specified path to the default path bootstrap In the path ;
-Xbootclasspath/p:path
  Give Way jvm Prior to the bootstrap The default path loads all files in the specified path ;
 
-Xcheck:jni
  Yes JNI Function to attach check; here jvm Pass the verification to JNI The validity of function parameters , When illegal data is encountered in local code ,jmv Will report a fatal error and terminate ; Using this parameter will cause performance degradation , Please use with caution .
 
-Xfuture
  Give Way jvm Perform strict format checks on class files ( Default jvm No strict format check ), To conform to the class file format specification , It is recommended that developers use this parameter .
 
-Xnoclassgc
  Turn off for class Of gc function ; Because it prevents memory recycling , So it could lead to OutOfMemoryError error , Use with caution ;
 
-Xincgc
  Turn on increment gc( The default is off ); This helps to reduce the amount of time GC A pause in the application ; But due to the possibility of concurrent execution with the application , So it will lower CPU The ability to process applications .
 
-Xloggc:file
  And -verbose:gc The function is similar to , Just every time GC The event is recorded in a file , The location of the file is better to be local , To avoid the potential problems of the network .
  If and verbose The command appears on the command line at the same time , with -Xloggc Subject to .
 
-Xmsn
  Appoint jvm The initial size of the heap , Default to physical memory 1/64, The minimum is 1M; You can specify units , such as k、m, If not specified , The default is byte .
 
-Xmxn
  Appoint jvm The maximum of the heap , Default to physical memory 1/4 perhaps 1G, The minimum is 2M; Unit and -Xms Agreement .
 
-Xprof
  Track running programs , And output the tracking data in the standard output ; Suitable for development environment debugging .
 
-Xrs
  Reduce jvm For operating system signals (signals) Use , The parameter is from 1.3.1 Start effective ;
  from jdk1.3.0 Start ,jvm Allows the program to execute some code before closing ( For example, close the database connection pool ), Even if jvm Be suddenly terminated ;
 jvm The shutdown tool meets the above functions by monitoring the relevant events of the console ; More precisely , Notify before closing tool execution , First register the control of the console handler, Then on CTRL_C_EVENT, CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, and CTRL_SHUTDOWN_EVENT These types of events return directly to true.
  But if jvm Run in the background as a service ( such as servlet engine ), He can accept CTRL_LOGOFF_EVENT event , But there is no need to initialize the shutdown program at this time ; by To avoid the recurrence of similar conflicts , from jdk1.3.1 Start offering -Xrs Parameters ; When this parameter is set ,jvm Will not receive control from the console handler, That means he doesn't monitor And handling CTRL_C_EVENT, CTRL_CLOSE_EVENT, CTRL_LOGOFF_EVENT, or CTRL_SHUTDOWN_EVENT event .
 
-Xssn
  Set the size of a single thread stack , The general default is 512k. 

Of the above parameters , such as -Xmsn、-Xmxn…… These are very important parameters in our performance optimization ;
-Xprof、-Xloggc:file They are good at troubleshooting without professional tracking tools ;
About... Mentioned in the previous section JProfiler In the configuration of -Xbootclasspath/a:path;



We mentioned earlier that -XX The list of parameters as a prefix is in jvm May not be robust ,SUN It is not recommended to use , The follow-up may be cancelled directly without notice ; But because many of these parameters are very useful to us , For example, we often see -XX:PermSize、-XX:MaxPermSize wait ;

Let's make do with Java HotSpot VM in -XX: A list of configurable parameters is described ;
These parameters can be loosely aggregated into three categories :
Behavioral parameters (Behavioral Options): Used to change jvm Some basic behaviors of ;
performance tuning (Performance Tuning): be used for jvm Performance tuning ;
Debug parameters (Debugging Options): It is generally used to turn on tracking 、 Print 、 Output, etc jvm Parameters , Used for display jvm More detailed information ;

because sun There are very few descriptions of parameters in official documents ( Most of them have only one sentence ), And most of them involve OS Level things , It's hard to describe clearly , So here are some configuration items that we may use more in development , If you need to see a list of all parameters , You can click on the  HotSpot VM Specific Options. Look at the original ;

First of all, let's introduce Behavioral parameters

Parameters and their default values describe
-XX:-DisableExplicitGC Ban called System.gc(); but jvm Of gc Still valid
-XX:+MaxFDLimit Maximize the number of file descriptors
-XX:+ScavengeBeforeFullGC The new generation GC Prior to the Full GC perform
-XX:+UseGCOverheadLimit Throwing out OOM Previous restrictions jvm Spend on GC The proportion of time on
-XX:-UseConcMarkSweepGC For the older generation, the concurrent label exchange algorithm is used GC
-XX:-UseParallelGC Enable parallel GC
-XX:-UseParallelOldGC Yes Full GC Enable parallel , When -XX:-UseParallelGC When enabled, this item is automatically enabled
-XX:-UseSerialGC Enable serial GC
-XX:+UseThreadPriorities Enable local thread priority

















The three parameters in bold in the table above represent jvm in GC Three ways of execution , namely Serial 、 parallel 、 Concurrent ;
Serial (SerialGC) yes jvm Default GC The way , Single processor and general applications , The algorithm is simple ,GC It's also more efficient , But it may bring pause to the application ;
parallel (ParallelGC) Refer to GC Runtime , No impact on application operation ,GC and app Both threads execute concurrently , This will minimize the impact on app Operation of ;
Concurrent (ConcMarkSweepGC) It refers to the concurrent execution of multiple threads GC, It is generally applicable to multiprocessor systems , Can improve GC The efficiency of , But the algorithm is complex , The system consumes a lot ;


performance tuning
parameter list :

 

Parameters and their default values describe
-XX:LargePageSizeInBytes=4m Setting is used for Java The big page size of the heap
-XX:MaxHeapFreeRatio=70 GC after java The largest proportion of idle space in the pile
-XX:MaxNewSize=size The maximum amount of memory that a newly generated object can occupy
-XX:MaxPermSize=64m The maximum amount of memory that an aging object can occupy
-XX:MinHeapFreeRatio=40 GC after java The minimum proportion of free space in the pile
-XX:NewRatio=2 The ratio of the memory capacity of the new generation to that of the old generation
-XX:NewSize=2.125m The default value of memory used when generating new generation objects
-XX:ReservedCodeCacheSize=32m Reserve the memory capacity of the code
-XX:ThreadStackSize=512 Set thread stack size , if 0 Then use the system default value
-XX:+UseLargePages Use large page memory


















In daily performance tuning, we will basically use the above attributes in bold ; 

Debug parameters list :

 

Parameters and their default values describe
-XX:-CITime Print consumption in JIT Compile time
-XX:ErrorFile=./hs_err_pid<pid>.log Save the error log or data to a file
-XX:-ExtendedDTraceProbes Turn on solaris Peculiar dtrace probe
-XX:HeapDumpPath=./java_pid<pid>.hprof Specifies the path or filename when exporting heap information
-XX:-HeapDumpOnOutOfMemoryError When first encountered OOM Export the relevant information in the heap at this time
-XX:OnError="<cmd args>;<cmd args>" It's deadly ERROR Then run the custom command
-XX:OnOutOfMemoryError="<cmd args>;<cmd args>" When first encountered OOM Execute the custom command
-XX:-PrintClassHistogram encounter Ctrl-Break Print the column information of the class instance , And jmap -histo Function the same
-XX:-PrintConcurrentLocks encounter Ctrl-Break Then print the information about the concurrent lock , And jstack -l Function the same
-XX:-PrintCommandLineFlags Print the tags that appear on the command line
-XX:-PrintCompilation Print information when a method is compiled
-XX:-PrintGC Every time GC When printing relevant information
-XX:-PrintGC Details Every time GC When printing details
-XX:-PrintGCTimeStamps Print every time GC The timestamp
-XX:-TraceClassLoading Tracking class loading information
-XX:-TraceClassLoadingPreorder Track the loading information of all classes referenced
-XX:-TraceCla***esolution Trace constant pool
-XX:-TraceClassUnloading Track class unload information
-XX:-TraceLoaderConstraints Keep track of class loader constraints


































When there's a problem with the system , You can't use external tracking tools ( such as JProfiler……) Under the circumstances , The above parameters will play a significant role , such as dump Heap information 、 Print concurrent locks ……

 

 

----------------------- The second understanding ------------------

Whether it's YGC still Full GC,GC During the process, the program will be interrupted , The right choice Different GC Strategy , adjustment JVM、GC Parameters of , Can be greatly reduced by GC Work , And caused by the interruption of program operation , And then improve it properly Java The efficiency of the program . But adjust GC It's a very A complex process , Because each program has different characteristics , Such as :web and GUI There's a big difference in the process (Web Can pause properly , but GUI A pause is unacceptable to the customer ), And because of running in all The configurations on the two machines are different ( The main cup Number , Memory is different ), So the GC There will be different kinds ( How to choose see GC Type and how to choose ). This article will focus on the introduction of JVM、GC To improve the performance of the system .

       JVM Memory composition and GC Please refer to the previous article :JVM The memory of  GC Strategy & Memory application .

JVM Meaning of parameters See for example The example analysis

Parameter name meaning The default value is  
-Xms Initial heap size Physical memory 1/64(<1GB) Default (MinHeapFreeRatio Parameters can be adjusted ) The free heap memory is less than 40% when ,JVM It's going to pile up until -Xmx The maximum limit of .
-Xmx Maximum heap size Physical memory 1/4(<1GB) Default (MaxHeapFreeRatio Parameters can be adjusted ) The free heap memory is larger than 70% when ,JVM It will reduce the pile until -Xms The minimum limit of
-Xmn Young generation size (1.4or lator)   Be careful : The size here is (eden+ 2 survivor space). And jmap -heap Shown in New gen Is different .
The whole pile size = Young generation size + Old generation size + Lasting generation size .
After increasing the younger generation , It will reduce the size of the old generation . This value has a great influence on the system performance ,Sun The official recommendation is to configure the entire heap as 3/8
-XX:NewSize Set younger generation size (for 1.3/1.4)    
-XX:MaxNewSize Young generation maximum (for 1.3/1.4)    
-XX:PermSize Set persistent generation (perm gen) Initial value Physical memory 1/64  
-XX:MaxPermSize Set persistent generation maximum Physical memory 1/4  
-Xss Stack size per thread   JDK5.0 After that, the stack size of each thread is 1M, Previously, the stack size of each thread was 256K. More memory size required by application thread adjustment . In the same physical memory , Reducing this value can generate more threads . But the operating system has a limit on the number of threads in a process , Can't generate... Indefinitely , Experience is in 3000~5000 about
Small applications in general , If the stack is not deep , Should be 128k Sufficient It is recommended to use 256k. This option has a big impact on performance , It needs strict testing .( The headmaster )
and threadstacksize The explanation of the options is very similar , The official documents do not seem to explain , There is such a sentence in the Forum :"”
-Xss is translated in a VM flag named ThreadStackSize”
Generally, you can set this value .
-XX:ThreadStackSize Thread Stack Size   (0 means use default stack size) [Sparc: 512; Solaris x86: 320 (was 256 prior in 5.0 and earlier); Sparc 64 bit: 1024; Linux amd64: 1024 (was 0 in 5.0 and earlier); all others 0.]
-XX:NewRatio The younger generation ( Include Eden And two Survivor District ) The ratio to the old ( Remove the permanent generation )   -XX:NewRatio=4 The ratio of young generation to old generation is 1:4, The younger generation takes up the whole stack 1/5
Xms=Xmx And set up Xmn Under the circumstances , This parameter does not need to be set .
-XX:SurvivorRatio Eden District and Survivor Area size ratio   Set to 8, Two Survivor District and a Eden The ratio of regions is 2:8, One Survivor District accounts for the whole young generation 1/10
-XX:LargePageSizeInBytes The size of the memory page cannot be set too large , It will affect Perm Size   =128m
-XX:+UseFastAccessorMethods Fast optimization of the original type    
-XX:+DisableExplicitGC close System.gc()   This parameter needs to be strictly tested
-XX:MaxTenuringThreshold The maximum age of garbage   If set to 0 Words , Then the young generation does not go through Survivor District , Go straight to the old generation . For the older generation more applications , Can improve efficiency . If you set this value to a larger value , The younger generation will be in Survivor Area to be copied many times , This can increase the survival of the younger generation Time , Increase the probability of being recycled in the younger generation
This parameter is only in serial GC Only when effective .
-XX:+AggressiveOpts Speed up compilation    
-XX:+UseBiasedLocking Lock mechanism performance improvement    
-Xnoclassgc No garbage collection    
-XX:SoftRefLRUPolicyMSPerMB Every megaheap of free space SoftReference Life time of 1s softly reachable objects will remain alive for some amount of time after the last time they were referenced. The default value is one second of lifetime per free megabyte in the heap
-XX:PretenureSizeThreshold How much more objects are allocated directly in the old generation 0 Unit byte The new generation adopts Parallel Scavenge GC When is invalid
Another case of direct generation allocation is large array objects , And there is no external reference object in the array .
-XX:TLABWasteTargetPercent TLAB Occupy eden % of area 1%  
-XX:+CollectGen0First FullGC Whether it's first or not YGC false  

Parallel collector related parameters

-XX:+UseParallelGC Full GC use parallel MSC
( This is to be verified )
 

Choose garbage collector as parallel collector . This configuration is only valid for younger generation . Under the above configuration , The younger generation uses concurrent collection , The older generation still uses serial collection .( This is to be verified )

-XX:+UseParNewGC Set up the young generation to collect in parallel   But with CMS Collect and use at the same time
JDK5.0 above ,JVM It will be set according to the system configuration , So there's no need to set this value
-XX:ParallelGCThreads Number of threads in parallel collector   This value is best configured to equal the number of processors The same applies CMS
-XX:+UseParallelOldGC Old generation garbage collection method is parallel collection (Parallel Compacting)   This is JAVA 6 The parameter options that appear
-XX:MaxGCPauseMillis The longest garbage collection time of each young generation ( Maximum pause time )   If this time cannot be met ,JVM Will automatically adjust the size of the younger generation , To meet this value .
-XX:+UseAdaptiveSizePolicy Automatically select the size of the younger generation area and the corresponding Survivor Area ratio   After setting this option , The parallel collector will automatically select the size of the younger generation area and the corresponding Survivor Area ratio , To achieve the minimum corresponding time or collection frequency specified by the target system , This value is recommended when using parallel collectors , Keep it open .
-XX:GCTimeRatio Set the percentage of garbage collection time in the running time of the program   Formula for 1/(1+n)
-XX:+ScavengeBeforeFullGC Full GC Pre invocation YGC true Do young generation GC prior to a full GC. (Introduced in 1.4.1.)

CMS Related parameters

-XX:+UseConcMarkSweepGC Use CMS Memory collection   After configuring this in the test ,-XX:NewRatio=4 The configuration of has failed , Unknown cause . therefore , At this time, the size of the younger generation is the best -Xmn Set up .???
-XX:+AggressiveHeap     Trying to use a lot of physical memory
Optimization of long time and large memory usage , Can check computing resources ( Memory , Number of processors )
Need at least 256MB Memory
a large number of CPU/ Memory , ( stay 1.4.1 stay 4CPU There is already a lift on the )
-XX:CMSFullGCsBeforeCompaction How many times will memory compression occur   Because the concurrent collector does not compress the memory space , Arrangement , So running for a while will produce " debris ", Reduce the efficiency of operation . This value sets how many times to run GC Compress the memory space later , Arrangement .
-XX:+CMSParallelRemarkEnabled Lower the mark pause    
-XX+UseCMSCompactAtFullCollection stay FULL GC When , Compression of the old   CMS It doesn't move memory , therefore , It's very easy to produce debris , Cause insufficient memory , therefore , Memory compression will be enabled at this time . It's a good habit to add this parameter .
May affect performance , But it can eliminate debris
-XX:+UseCMSInitiatingOccupancyOnly Start with a manual definition initialization definition CMS collect   prohibit hostspot Self trigger CMS GC
-XX:CMSInitiatingOccupancyFraction=70 Use cms As garbage collection
Use 70% Later on CMS collect
92 In order not to appear promotion failed( See introduction below ) error , The setting of this value needs to meet the following formula CMSInitiatingOccupancyFraction Calculation formula
-XX:CMSInitiatingPermOccupancyFraction Set up Perm Gen Use the rate reached to trigger 92  
-XX:+CMSIncrementalMode Set to incremental mode   Used for single CPU situation
-XX:+CMSClassUnloadingEnabled      

Supporting information

-XX:+PrintGC    

Output form :

[GC 118250K->113543K(130112K), 0.0094143 secs]
[Full GC 121376K->10414K(130112K), 0.0650971 secs]

-XX:+PrintGCDetails    

Output form :[GC [DefNew: 8614K->781K(9088K), 0.0123035 secs] 118250K->113543K(130112K), 0.0124633 secs]
[GC [DefNew: 8614K->8614K(9088K), 0.0000665 secs][Tenured: 112761K->10414K(121024K), 0.0433488 secs] 121376K->10414K(130112K), 0.0436268 secs]

-XX:+PrintGCTimeStamps      
-XX:+PrintGC:PrintGCTimeStamps     But with -XX:+PrintGC -XX:+PrintGCDetails A mixture of
Output form :11.851: [GC 98328K->93620K(130112K), 0.0082960 secs]
-XX:+PrintGCApplicationStoppedTime Time the program paused during print garbage collection . Can be mixed with the above   Output form :Total time for which application threads were stopped: 0.0468229 seconds
-XX:+PrintGCApplicationConcurrentTime Print every time before garbage collection , The execution time of the program without interruption . Can be mixed with the above   Output form :Application time: 0.5291524 seconds
-XX:+PrintHeapAtGC Print GC Detailed stack information before and after    
-Xloggc:filename Record the relevant log information to a file for analysis .
Use in combination with the above
   

-XX:+PrintClassHistogram

garbage collects before printing the histogram.    
-XX:+PrintTLAB see TLAB Use of space    
XX:+PrintTenuringDistribution Check every time minor GC Threshold of new life cycle after  

Desired survivor size 1048576 bytes, new threshold 7 (max 15)
new threshold 7 That is to say, the threshold for identifying a new life cycle is 7.

GC Performance considerations

       about GC The main performance of 2 Indicators of all aspects : throughput throughput( Working hours don't count gc The ratio of time to total time ) And pause pause(gc occurs app Can't respond to external display ).

1. Total Heap

       By default ,vm Will increase / Reduce heap To maintain in size free space Throughout vm The proportion in , This ratio is determined by MinHeapFreeRatio and MaxHeapFreeRatio Appoint .

generally speaking ,server Terminal app There will be the following rules :

  • Yes vm Allocate as much as possible memory;
  • take Xms and Xmx Set to the same value . If the memory used for the virtual machine startup is relatively small , At this time, many objects need to be initialized , Virtual machines have to increase memory repeatedly .
  • Processor cores increase , Memory also increases .

2. The Young Generation

       The other one is for app What are the influencing factors of fluency young generation Size .young generation The bigger it is ,minor collection The less ; But it's fixed heap size Under the circumstances , Bigger young generation It means small tenured generation, It means more major collection(major collection May trigger minor collection).

       NewRatio Reflect the young and tenured generation In proportion to the size of .NewSize and MaxNewSize Reflect the young generation Lower and upper limits of size , If you set these two values to the same, it's fixed young generation Size ( Same as Xms and Xmx Set to the same ).

       If you want to ,SurvivorRatio Can also be optimized survivor Size , But it's not a big impact on performance .SurvivorRatio yes eden and survior Size ratio .

generally speaking ,server Terminal app There will be the following rules :

  • First of all, decide to allocate it to vm One of the biggest heap size, Then set the best young generation Size ;
  • If heap size After fixing , increase young generation The size of that means a reduction tenured generation size . Give Way tenured generation Big enough at any time , Can hold all live Of data( leave 10%-20% The spare time of ).

Experience && The rules

  1. Young generation size choice
    • Response time first applications : Make it as big as possible , Until near the minimum response time limit of the system ( Choose... According to the actual situation ). In this case , The frequency of young generation collection is also the smallest . meanwhile , Reduce the number of people who reach the elderly .
    • Throughput first applications : Set as large as possible , May arrive at Gbit The degree of . Because there is no requirement for response time , Garbage collection can be done in parallel , General fit 8CPU The above applications .
    • Avoid setting too small . When the new generation is set too small, it will lead to :1.YGC More often 2. May lead to YGC The object goes directly to the old generation , If the old generation is full at this time , Will trigger FGC.
  2. Size selection of the elderly
    1. ring Time first applications : The older generation uses concurrent collectors , So its size needs to be set carefully , Generally, some parameters such as concurrent session rate and session duration should be considered . If the heap setting is small , Can cause memory corruption slice , High recovery frequency and application pause using traditional tag removal ; If the pile is big , It takes a long time to collect . The best solution , Generally, you need to refer to the following data to obtain :
      Concurrent garbage collection information 、 The number of persistent generation concurrent collections 、 Tradition GC Information 、 The proportion of time spent recycling young and old .
    2. Throughput first applications : Generally, throughput priority applications have a large young generation and a small old generation . as a result of , In this way, most of the short-term objects can be recycled as much as possible , Reduce the number of objects in the medium term , The old generation should store the long-term survival objects .
  3. Debris problems caused by smaller piles
    because Use the tag... For older generations of concurrent collectors , Clear algorithm , So there's no compression on the heap . When the collector recovers , He will merge the adjacent spaces , This can be assigned to larger objects . however , When heap space More hours , After running for a while , Will appear " debris ", If the concurrent collector cannot find enough space , Then the concurrent collector will stop , Then use traditional markers , The removal method is used for recycling . If it comes out present " debris ", You may need to configure the following :
    -XX:+UseCMSCompactAtFullCollection: When using concurrent collectors , Turn on the compression of the old .
    -XX:CMSFullGCsBeforeCompaction=0: When the above configuration is on , How many times is it set here Full GC after , Compress the old generation
  4. use 64 Bit operating system ,Linux Next 64 Bit jdk Than 32 position jdk Slow down , But eat more memory , More throughput
  5. XMX and XMS The setting is the same size ,MaxPermSize and MinPermSize The setting is the same size , This can reduce the pressure of the size of the telescoping heap
  6. Use CMS The advantage is to use as few new generations as possible , The empirical value is 128M-256M, And then the old generation uses it CMS Parallel collection , This can ensure the low latency throughput of the system . actually cms The collection pause time of is very short ,2G Of memory , about 20-80ms Application pause time
  7. When the system stops, it may be GC The problem may also be the problem of the program , multi-purpose jmap and jstack see , perhaps killall -3 java, Then check it out java Console log , Can see a lot of problems .( The usage of related tools will be described in the following blog Described in the )
  8. Learn more about your application , If cache is used , So the old generation should be older , The cache HashMap It should not be unlimited , The proposal USES LRU Algorithm Map Do the cache ,LRUMap The maximum length of should also be set according to the actual situation .
  9. When using concurrent recycle , Younger generation is a little smaller , Old age is big , Because old age is a big use of concurrent recycling , Even if the time is long, it will not affect other programs to continue to run , The site doesn't stop
  10. JVM Parameter settings ( especially –Xmx –Xms –Xmn -XX:SurvivorRatio  -XX:MaxTenuringThreshold There is no fixed formula for parameter setting , Need basis PV old Area actual data YGC Number of times and so on . for fear of promotion faild May lead to xmn The setting is too small , Also means that YGC The number of times will increase , The ability to deal with concurrent access declines and so on . Every parameter adjustment needs to go through detailed performance test , To find special Determine the best configuration for the application .

promotion failed:

Garbage collection promotion failed It's a big headache , Generally, there are two reasons , The first reason is that there is not enough room for relief , Objects in the rescue space should not be moved to the older generation yet , But the younger generation has a lot of objects to need Put into the rescue space ; The second reason is that the older generation does not have enough space to accept objects from the younger generation ; Both will turn to Full GC, The website pauses for a long time .

Solution 1 :

The first One reason is that my final solution is to remove the rescue space , Set up -XX:SurvivorRatio=65536 -XX:MaxTenuringThreshold=0 that will do , The second reason is that my solution is to set up CMSInitiatingOccupancyFraction For a certain value ( hypothesis 70), So old generation space to 70% Start executing when CMS, The older generation has enough space to pick up Na is a target from the younger generation .

The improvement of solution one :

It's improved again , The above method is not very good , Because there's no space for rescue , the It is easy to fill with old age ,CMS Execution will be more frequent . I improved , Or space , But increase the space for relief , It's not going to happen promotion failed. Specific operation ,32 position Linux and 64 position Linux It seems different ,64 Bit system seems to be just configuration MaxTenuringThreshold ginseng Count ,CMS There is still a pause . In order to solve the suspension problem and promotion failed problem , Finally, I set -XX:SurvivorRatio=1 , And put MaxTenuringThreshold Get rid of , In this way, there will be no pause or promotoin failed, And more importantly , Old and permanent generations rise very slowly ( Because a lot of objects are recycled before they reach old age ), therefore CMS Execution frequency is very low , It takes hours to execute , this sample , No need to restart the server .

-Xmx4000M -Xms4000M -Xmn600M -XX:PermSize=500M -XX:MaxPermSize=500M -Xss256K -XX:+DisableExplicitGC -XX:SurvivorRatio=1 -XX:+UseConcMarkSweepGC -XX:+UseParNewGC -XX:+CMSParallelRemarkEnabled -XX:+UseCMSCompactAtFullCollection -XX:CMSFullGCsBeforeCompaction=0 -XX:+CMSClassUnloadingEnabled -XX:LargePageSizeInBytes=128M -XX:+UseFastAccessorMethods -XX:+UseCMSInitiatingOccupancyOnly -XX:CMSInitiatingOccupancyFraction=80 -XX:SoftRefLRUPolicyMSPerMB=0 -XX:+PrintClassHistogram -XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintHeapAtGC -Xloggc:log/gc.log

 

CMSInitiatingOccupancyFraction Value and Xmn The relation formula of

On Introduce promontion faild The reason for this is EDEN In the case of insufficient space, the EDEN And From survivor Live objects in To survivor Regional time ,To survivor There is not enough space in this area , Promotion again to old gen District , and old gen When there is not enough memory in the memory area, it produces promontion faild Which leads to full gc. It can be inferred that :eden+from survivor < old gen When memory is left , There will be no promontion faild The situation of , namely :
(Xmx-Xmn)*(1-CMSInitiatingOccupancyFraction/100)>=(Xmn-Xmn/(SurvivorRatior+2))  And then infer :

CMSInitiatingOccupancyFraction <=((Xmx-Xmn)-(Xmn-Xmn/(SurvivorRatior+2)))/(Xmx-Xmn)*100

for example :

When xmx=128 xmn=36 SurvivorRatior=1 when CMSInitiatingOccupancyFraction<=((128.0-36)-(36-36/(1+2)))/(128-36)*100 =73.913

When xmx=128 xmn=24 SurvivorRatior=1 when CMSInitiatingOccupancyFraction<=((128.0-24)-(24-24/(1+2)))/(128-24)*100=84.615…

When xmx=3000 xmn=600 SurvivorRatior=1 when   CMSInitiatingOccupancyFraction<=((3000.0-600)-(600-600/(1+2)))/(3000-600)*100=83.33

CMSInitiatingOccupancyFraction lower than 70% Need to adjust xmn or SurvivorRatior value .

Make :

  A pair of children's shoes on the Internet The inferred formula is ::(Xmx-Xmn)*(100-CMSInitiatingOccupancyFraction)/100>=Xmn Personally, I don't think this formula is very rigorous , When the memory is small, it will affect xmn The calculation of .

 

About the actual environment GC See... For parameter configuration : The example analysis    See for monitoring tools JVM monitoring

Reference resources :

JAVA HOTSPOT VM( http://www.helloying.com/blog/archives/164

 JVM Several important parameters ( The headmaster )

 java jvm Parameters -Xms -Xmx -Xmn -Xss Tuning summary

 Java HotSpot VM Options

 http://bbs.weblogicfans.net/archiver/tid-2835.html

 Frequently Asked Questions About the Java HotSpot VM

 Java SE HotSpot at a Glance

Java Performance tuning notes ( Test examples are attached It is useful to )

  say something MaxTenuringThreshold This parameter

 

Recommended articles :

GC Summary of tuning methods

 Java 6 JVM Parameter options ( Chinese version )

 

【 When you write every blog with your heart , You'll find that it's more fulfilling than you do with code !】
 
 
 
 

版权声明
本文为[wx58f0846670609]所创,转载请带上原文链接,感谢
https://chowdera.com/2021/08/20210802134759573r.html

随机推荐