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

JVM runtime parameters

2022-06-12 13:07:00 Li_ XiaoJin

JVM Runtime parameters

1.JVM Parameter options

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

1.1. Type 1 : Standard parameter options

> java -help
 usage : java [-options] class [args...]
           ( Executive class )
    or   java [-options] -jar jarfile [args...]
           ( perform  jar  file )
 The options include :
    -d32           Use  32  Bit data model  ( If available )
    -d64           Use  64  Bit data model  ( If available )
    -server        choice  "server" VM
                   Default  VM  yes  server.

    -cp < Contents and  zip/jar  Class search path for file >
    -classpath < Contents and  zip/jar  Class search path for file >
                   use  ;  Separate directories , JAR  archives 
                   and  ZIP  File list ,  Used to search 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 feature is out of date ,  Will be in 
                   Delete... In future releases .
                   The specified version is required to run 
    -showversion   Output the product version and continue 
    -jre-restrict-search | -no-jre-restrict-search
                   Warning :  This feature is out of date ,  Will be in 
                   Delete... In future releases .
                   Include... In version search / Exclusive to users  JRE
    -? -help       Output this help message 
    -X             Output help for non-standard options 
    -ea[:<packagename>...|:<classname>]
    -enableassertions[:<packagename>...|:<classname>]
                   Enable assertions at the specified granularity 
    -da[:<packagename>...|:<classname>]
    -disableassertions[:<packagename>...|:<classname>]
                   Disable assertions with specified granularity 
    -esa | -enablesystemassertions
                   Enable system assertion 
    -dsa | -disablesystemassertions
                   Disable system assertion 
    -agentlib:<libname>[=< Options >]
                   Load native agent Library  <libname>,  for example  -agentlib:hprof
                   See also  -agentlib:jdwp=help  and  -agentlib:hprof=help
    -agentpath:<pathname>[=< Options >]
                   Load the native agent library by the full pathname 
    -javaagent:<jarpath>[=< Options >]
                   load  Java  Programming language agent ,  see also  java.lang.instrument
    -splash:<imagepath>
                   Use the specified image to display the start screen 
 For more information ,  see also  http://www.oracle.com/technetwork/java/javase/documentation/index.html.

Server Patterns and Client Pattern

Hotspot JVM There are two patterns , Namely server and client, Pass respectively -server and -client Mode setting

  • 32 Bit system , By default Client Type of JVM. Want to use Server Pattern , The machine configuration has at least 2 More than one CPU and 2G The physical memory above .client Mode is suitable for desktop applications that require less memory , By default Serial Serial garbage collector
  • 64 Bit system , Only support server Mode JVM, For applications that require large memory , Parallel garbage collectors are used by default

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

How to know which mode the system uses by default ?

adopt java -version command : You can see Server VM word , Representing the current system usage is Server Pattern

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

1.2. Type 2 :-X Parameter options

> java -X
    -Xmixed            Mixed mode execution  ( Default )
    -Xint              Explain only mode execution 
    -Xbootclasspath:< use  ;  Separate directories and  zip/jar  file >
                       Set search paths to guide classes and resources 
    -Xbootclasspath/a:< use  ;  Separate directories and  zip/jar  file >
                       Attached at the end of the boot class path 
    -Xbootclasspath/p:< use  ;  Separate directories and  zip/jar  file >
                       Before the boot class path 
    -Xdiag             Display additional diagnostic messages 
    -Xnoclassgc        Disable garbage collection 
    -Xincgc            Enable incremental garbage collection 
    -Xloggc:<file>     take  GC  The status is recorded in the file  ( With a time stamp )
    -Xbatch            Disable background compilation 
    -Xms<size>         Set the initial  Java  Heap size 
    -Xmx<size>         Set the maximum  Java  Heap size 
    -Xss<size>         Set up  Java  Thread stack size 
    -Xprof             Output  cpu  Profile data 
    -Xfuture           Enable the most stringent checks ,  Expected future defaults 
    -Xrs               Reduce  Java/VM  Use of operating system signals  ( See documentation )
    -Xcheck:jni        Yes  JNI  Function to perform other checks 
    -Xshare:off        Don't try to use shared class data 
    -Xshare:auto       Use shared class data when possible  ( Default )
    -Xshare:on         Require shared data ,  Otherwise it will fail .
    -XshowSettings     Show all settings and continue 
    -XshowSettings:all
                       Show all settings and continue 
    -XshowSettings:vm  Show all and  vm  Related settings and continue 
    -XshowSettings:properties
                       Show all property settings and continue 
    -XshowSettings:locale
                       Show all locale related settings and continue 

-X  Options are nonstandard options ,  If there is any change ,  Without notice .

How do you know JVM Mixed mode is used by default ?

similarly , adopt java -version command : You can see mixed mode word , Representing the current system using mixed mode

1.3. Type 3 :-XX Parameter options

Boolean Type format

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

Not Boolean Type format

-XX:<option>=<number>   Set up option The number , You can bring units like k/K/m/M/g/G
-XX:<option>=<string>   Set up option Character value 

2. add to JVM Parameter options

eclipse and idea I don't need to say much about the configuration in , stay Run Configurations in VM Options Medium configuration is ok , Be the same in essentials while differing in minor points

function jar package

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

Tomcat function war package

# linux Next catalina.sh add to 
JAVA_OPTS="-Xms512M -Xmx1024M"
# windows Next catalina.bat add to 
set "JAVA_OPTS=-Xms512M -Xmx1024M"

The program is running

#  Set up Boolean Type parameter 
jinfo -flag [+|-]<name> <pid>
#  Set not to Boolean Type parameter 
jinfo -flag <name>=<value> <pid>

3. frequently-used JVM Parameter options

3.1. Print settings for XX Options and values

-XX:+PrintCommandLineFlags  Program runtime JVM Default settings or manually set by the user XX Options 
-XX:+PrintFlagsInitial  Print all XX The default value of the option 
-XX:+PrintFlagsFinal  Print all XX The actual value of the option 
-XX:+PrintVMOptions  Print JVM Parameters of 

3.2. Pile up 、 Stack 、 Method area and other memory size settings

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

#  Pile up 
-Xms2048m <==> -XX:InitialHeapSize=2048m  Set up JVM The initial heap memory is 2048M
-Xmx2048m <==> -XX:MaxHeapSize=2048m  Set up JVM The maximum heap memory is 2048M
-Xmn2g <==> -XX:NewSize=2g -XX:MaxNewSize=2g  Set the size of the younger generation to 2G
-XX:SurvivorRatio=8  Set up Eden District and Survivor Area ratio , The default is 8
-XX:NewRatio=2  Set the ratio between the old and the young , The default is 2
-XX:+UseAdaptiveSizePolicy  Set size scale adaptive , Default on 
-XX:PretenureSizeThreadshold=1024  The setting allows objects larger than this threshold to be allocated directly to the older generation , Only right Serial、ParNew Collector valid 
-XX:MaxTenuringThreshold=15  Set the age limit for the new generation to promote the old generation , The default is 15
-XX:TargetSurvivorRatio  Set up MinorGC After the end Survivor The expected proportion of space occupied by the zone 

#  Method area 
-XX:MetaspaceSize / -XX:PermSize=256m  Set up the meta space / The initial value of permanent generation is 256M
-XX:MaxMetaspaceSize / -XX:MaxPermSize=256m  Set up the meta space / The maximum value of permanent generation is 256M
-XX:+UseCompressedOops  Use compressed objects 
-XX:+UseCompressedClassPointers  Use compressed class pointers 
-XX:CompressedClassSpaceSize  Set up Klass Metaspace Size , Default 1G

#  Direct memory 
-XX:MaxDirectMemorySize  Appoint DirectMemory Capacity , Default equal to Java Heap maximum 

3.3. OutOfMemory Related options

-XX:+HeapDumpOnOutMemoryError  Memory appears OOM Time generation Heap Dump files , The two are mutually exclusive 
-XX:+HeapDumpBeforeFullGC  appear FullGC Time generation Heap Dump files , The two are mutually exclusive 
-XX:HeapDumpPath=<path>  Appoint heap The storage path of the dump file , Default current directory 
-XX:OnOutOfMemoryError=<path>  Specify the path to the feasibility program or script , Happen when OOM When the script is executed 

3.4. Garbage collector related options

First of all, we need to understand the collocation relationship between garbage collectors

  • The red dotted line indicates that jdk8 When I was Deprecate,jdk9 Is deleted
  • The dotted green line indicates that jdk14 When I was Deprecate
  • The empty green box means jdk9 When I was Deprecate,jdk14 Is deleted

# Serial Recyclers 
-XX:+UseSerialGC   The younger generation uses Serial GC,  Used in the old days Serial Old GC
# ParNew Recyclers 
-XX:+UseParNewGC   The younger generation uses ParNew GC
-XX:ParallelGCThreads   Set the number of threads for the younger generation of parallel collectors .
     In a general way , Best and CPU Equal quantity , To avoid the impact of too many threads on garbage collection performance .

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

# Parallel Recyclers 
-XX:+UseParallelGC   The younger generation uses  Parallel Scavenge GC, Activate each other 
-XX:+UseParallelOldGC   Used in the old days  Parallel Old GC, Activate each other 
-XX:ParallelGCThreads
-XX:MaxGCPauseMillis   Set the maximum pause time for the garbage collector ( namely STW Time for ), In milliseconds .
     In order to control the pause time as much as possible MaxGCPauseMills within , The collector adjusts as it works Java Heap size or some other parameters .
     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 . This parameter should be used with caution .
-XX:GCTimeRatio   The proportion of garbage collection time to total time (1 / (N+1)), Used to measure throughput 
     Value range (0,100), The default value is 99, That is, the garbage collection time should not exceed 1%.
     With the previous -XX:MaxGCPauseMillis There are some contradictions in the parameters . The longer the pause is ,Radio The parameter is easy to exceed the set ratio .
-XX:+UseAdaptiveSizePolicy   Set up Parallel Scavenge The collector has an adaptive tuning strategy .
     In this mode , The size of the younger generation 、Eden and Survivor The proportion of 、 Parameters such as the age of the person who is promoted to the old age will be automatically adjusted , To reach the heap size 、 The balance between throughput and pause time .
     Where manual tuning is difficult , You can use this adaptive approach directly , Only specify the maximum heap for the virtual machine 、 Target throughput (GCTimeRatio) And pause time (MaxGCPauseMills), Let the virtual machine do its own tuning .
# CMS Recyclers 
-XX:+UseConcMarkSweepGC   The younger generation uses CMS GC.
     When this parameter is turned on, the -XX:+UseParNewGC open . namely :ParNew(Young District )+ CMS(Old District )+ Serial Old The combination of 
-XX:CMSInitiatingOccupanyFraction   Set the threshold for heap memory usage , Once that threshold is reached , And we started recycling .JDK5 The default values for and before are 68,DK6 And above, the default value is 92%.
     If memory growth is slow , You can set a slightly larger value , A large threshold can effectively reduce CMS The trigger frequency of , Reducing the number of recycling in the old age can significantly improve application performance .
     conversely , If application memory usage is growing fast , The threshold should be lowered , To avoid frequent triggering of old age serial collectors .
     Therefore, this option can effectively reduce Fu1l GC Number of executions .
-XX:+UseCMSInitiatingOccupancyOnly   Whether it is dynamically adjustable , send CMS Keep pressing CMSInitiatingOccupancyFraction Set the value to start 
-XX:+UseCMSCompactAtFullCollection   Used to specify at the end of execution Full GC After the memory space compression finishing 
     To avoid memory fragmentation . However, due to memory compression, the grooming process cannot be executed concurrently , The problem is that the pause is getting longer .
-XX:CMSFullGCsBeforeCompaction   Set how many times to execute Full GC After the memory space compression finishing .
-XX:ParallelCMSThreads   Set up CMS Number of threads .
    CMS  The default number of threads to start is (ParallelGCThreads+3)/4,ParallelGCThreads  Is the number of threads in the younger generation of parallel collectors .
     When CPU  When resources are tight , suffer CMS The impact of collector threads , The performance of an application can be very poor during the garbage collection phase .
-XX:ConcGCThreads   Set the number of threads for concurrent garbage collection , The default value is based on ParallelGCThreads Calculated 
-XX:+CMSScavengeBeforeRemark   mandatory hotspot stay cms remark Do it before the stage minor gc, For improvement remark The speed of the stage 
-XX:+CMSClassUnloadingEnable   If any , Enable recycle Perm  District (JDK8 Before )
-XX:+CMSParallelInitialEnabled   For opening CMS initial-mark The stage is marked by multi thread 
     Used to increase marking speed , stay Java8 Start has been turned on by default 
-XX:+CMSParallelRemarkEnabled   User on CMS remark The stage is marked again by multi thread , Default on 
-XX:+ExplicitGCInvokesConcurrent
-XX:+ExplicitGCInvokesConcurrentAndUnloadsClasses
     These two parameters are user specified hotspot Virtual reality is performing System.gc() When using CMS cycle 
-XX:+CMSPrecleaningEnabled   Appoint CMS Is it necessary to Pre cleaning Stage 
# G1 Recyclers 
-XX:+UseG1GC  Manually specify the use of G1 The collector performs the memory reclaim task .
-XX:G1HeapRegionSize  Set each Region Size .
     The value is 2 The power of , The scope is 1MB To 32MB Between , The goal is based on the smallest Java The heap size is divided into about 2048 Regions . The default is heap memory 1/2000.
-XX:MaxGCPauseMillis   Set the maximum expected GC Pause time indicator (JVM I will try my best to achieve , But there is no guarantee that ). The default value is 200ms
-XX:ParallelGCThread   Set up STW when GC The value of the number of threads . The maximum setting is 8
-XX:ConcGCThreads   Set the number of threads for concurrent tagging . take n Set to the number of parallel garbage collection threads (ParallelGCThreads) Of 1/4 about .
-XX:InitiatingHeapOccupancyPercent  Set trigger concurrency GC Periodic Java Heap occupancy threshold . Beyond this value , It triggers GC. The default value is 45.
-XX:G1NewSizePercent   The minimum percentage of the whole heap memory occupied by the new generation ( Default 5%)
-XX:G1MaxNewSizePercent   The largest percentage of the whole heap memory occupied by the new generation ( Default 60%)
-XX:G1ReservePercent=10   Reserve memory area , prevent  to space(Survivor Medium to District ) overflow 

How to choose a garbage collector ?

  • Give priority to JVM The adaptive , Size the heap
  • Serial collector : Memory less than 100M; Single core 、 Stand alone program , And there is no pause time requirement
  • Parallel collector : many CPU、 High throughput 、 Allow a pause longer than 1 second
  • concurrent collector : many CPU、 Pursue low pause time 、 Respond quickly ( For example, the delay cannot exceed 1 second , Such as Internet applications )
  • The official recommendation G1, High performance . Now the Internet Project , It's basically using G1

In particular :

  • There is no best collector , There is no universal collector
  • Tuning is always for specific scenarios 、 Specific needs , There is no collector for once and for all

3.5. GC Log related options

-XX:+PrintGC <==> -verbose:gc   Print brief log information 
-XX:+PrintGCDetails             Print detailed log information 
-XX:+PrintGCTimeStamps   Print program starts to GC When it happened , collocation -XX:+PrintGCDetails Use 
-XX:+PrintGCDateStamps   Print GC Time stamp when it happened , collocation -XX:+PrintGCDetails Use 
-XX:+PrintHeapAtGC   Print GC Front and back heap information , Here's the picture 
-Xloggc:<file>  Output GC In the file under the specified path 

-XX:+TraceClassLoading   Monitor the loading of classes 
-XX:+PrintGCApplicationStoppedTime   Print GC The pause time of the thread 
-XX:+PrintGCApplicationConcurrentTime   Apply uninterrupted execution time before printing garbage collection 
-XX:+PrintReferenceGC  Print how many different reference types are recycled 
-XX:+PrintTenuringDistribution   Print JVM In every time MinorGC After the current use of Survivor The age distribution of the subjects in the study 
-XX:+UseGCLogFileRotation  Enable GC Automatic dump of log files 
-XX:NumberOfGCLogFiles=1   Set up GC Number of cycles for the log file 
-XX:GCLogFileSize=1M   Set up GC The size of the log file 

3.6. The other parameters

-XX:+DisableExplicitGC   Ban hotspot perform System.gc(), Default disabled 
-XX:ReservedCodeCacheSize=<n>[g|m|k]、-XX:InitialCodeCacheSize=<n>[g|m|k]   Specify the size of the code cache 
-XX:+UseCodeCacheFlushing   Give up some compiled code , Avoid when the code cache is full JVM Switch to interpreted-only The situation of 
-XX:+DoEscapeAnalysis   Open escape analysis 
-XX:+UseBiasedLocking   Open the bias lock 
-XX:+UseLargePages   Open and use the big page 
-XX:+PrintTLAB   Print TLAB Usage situation 
-XX:TLABSize   Set up TLAB size 

4. adopt Java Code acquisition JVM Parameters

Java Provides java.lang.management Packages are used to monitor and manage Java Virtual machine and Java Other components in the runtime , It allows local or remote monitoring and management of running Java virtual machine . among ManagementFactory Class is more commonly used , in addition Runtime Class to get memory 、CPU Kernel number and other related data . By using these api, You can monitor the heap memory usage of the application server , Set some 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("======================= adopt java To get the relevant system status ============================ ");
        System.out.println(" Current heap memory size totalMemory " + (int) Runtime.getRuntime().totalMemory() / 1024 / 1024 + "m");//  Current heap memory size 
        System.out.println(" Free heap memory size freeMemory " + (int) Runtime.getRuntime().freeMemory() / 1024 / 1024 + "m");//  Free heap memory size 
        System.out.println(" Maximum available total heap memory maxMemory " + Runtime.getRuntime().maxMemory() / 1024 / 1024 + "m");//  Maximum available total heap memory size 

    }
}

Copyright: use Creative Commons signature 4.0 International license agreement to license Links:https://lixj.fun/archives/jvm Runtime parameters

原网站

版权声明
本文为[Li_ XiaoJin]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/163/202206121248379775.html