preface

The first five articles in the JVM series are relatively theoretical, starting with an analysis of real-world scenarios and how to tune the JVM.

The JVM parameter

JVM tuning is simply about setting parameters that are reasonable and appropriate for the JVM on your current system. In general, JVM parameters can be divided into three main categories: standard parameters, -x parameters, and -xx parameters.

Standard parameters

Parameters starting with “-” are called standard parameters. Standard parameters are supported by all JDK versions and are relatively stable and generally do not change with JDK versions. Such as:

-version
-help
-server
-cp
Copy the code

– X parameter

Arguments starting with -x are commands supported in a particular version of HotSpot and may change after JDK versions change. This parameter is used sparingly. Such as the following:

-xint interprets execution -Xcomp compilers code the first time it is used -Xmixed mode, the JVM itself decidesCopy the code

This kind of parameter is used less, understand can, here will not do the demonstration

XX parameters –

-xx is an unstable parameter that may be cancelled in the next version. -xx is the main parameter for JVM tuning. -XX parameters can be Boolean or non-Boolean.

Boolean type

Boolean -xx arguments are in the format:

-xx :[+-]<name> + or - Indicates whether the name attribute is enabled or disabledCopy the code

Such as:

-xx :+UseConcMarkSweepGC enables CMS garbage collector. -xx :+UseG1GC enables G1 garbage collector. -xx :+PrintFlagsFinal prints all JVM parameter informationCopy the code

Prints all JVM parameters

Let’s use -xx :+PrintFlagsFinal to print out all the parameters. Let’s see:

package com.zwx.jvm; public class TestJVMParam { public static void main(String[] args) { System.out.println(11); }}Copy the code

I am using the IntelliJ IDEA tool and select: Run — >Edit Configurations. Then click the + on the left and select Application. You will see the following screen and add JVM parameters:



Then run the main method, which prints out all the arguments (there are more than 700) :



Note: In the printed parameters in the figure above

“=” indicates the default value, and “:=” indicates the value modified by the user or JVM

The Boolean type

The format for the non-boolean -xx argument is:

-xx <name>=<value> name indicates the attribute, and value indicates the value of the attributeCopy the code

Such as:

-xx :MaxMetaspaceSize=5M Set the maximum permanent generation size (jdk1.8)Copy the code

The other parameters

-xms, -xmx, and -xss are some of the most common arguments, but they are also -xx arguments, which are just shorthand for convenience. So a search for -xms, -xmx, -xss in the arguments printed above will not be found.

-xMS1000 is equivalent to -xx :InitialHeapSize=1000 -XMx1000 is equivalent to -xx :MaxHeapSize=1000 -xSS100 is equivalent to -xx :ThreadStackSize=100Copy the code

Common JVM parameters

parameter meaning instructions
-XX:CICompilerCount=3 Maximum number of parallel compilations Higher than 1 can improve compilation speed, but it can affect system stability and increase the likelihood of JVM crashes
-XX:InitialHeapSize=100M Initialize the heap size Short – Xms100M
-XX:MaxHeapSize=100M Maximum heap size Short – Xmx100M
-XX:NewSize=20M Sets the size of the young generation
-XX:MaxNewSize=50M Maximum size of young generation
-XX:OldSize=50M Set the age size
-XX:MetaspaceSize=50M Set the size of the method area Jdk1.8, the use of meta-space to achieve the method area
-XX:MaxMetaspaceSize=50M Maximum size of method area Jdk1.8, the use of meta-space to achieve the method area
-XX:+UseParNewGC Set ParNe as the New generation collector Serial Old is chosen by default to work with it as the old age collector
-XX:+UseParallelGC The Parallel Collector is insane, and the Parallel Old collector is selected by default This combination is the default combination of throughput first garbage collectors in jdk1.8
-XX:+UseParallelOldGC Insane. Set the Parallel Old garbage collector to the Parallel Avenge avenge
-XX:+ParallelGCThreads Set the number of concurrent garbage collection threads Generally set to the same number of cpus, this parameter also applies to the CMS collector
-XX:+UseConcMarkSweepGC Select CMS as the old collector and ParNew as the new collector by default If a Concurrent Mode Failure occurs in the CMS collector, it switches to Serial Old for the Old age collector
-XX:+CMSScavengeBeforeRemark The CMS collector does a Young GC before the final tag
-XX:CMSMaxAbortablePrecleanTime Maximum dwell time for the interruptible pre-cleanup phase of the CMS collector The default is 5000 milliseconds
-XX:+UseG1GC Use G1 as the collector For both the new generation and the old generation, it is a pause-first garbage collector, the default garbage collector in jdk1.9
-XX:NewRatio Ratio of neoproterozoic For example, -xx :Ratio=4, it means that the new generation: the old age =1:4
-XX:SurvivorRatio Ratio of the two S-blocks to Eden For example, -xx :SurvivorRatio=8, i.e. (S0+S1):Eden=2:8
-XX:+HeapDumpOnOutOfMemoryError Start heap overflow printing Dump files are automatically generated when JVM heap memory overflows (i.e. OOM)
-XX:HeapDumpPath=heap.hprof Specifies the heap overflow print directory Generates a heap. Hprof file in the current directory
-XX:+PrintGCDetails -XX:+PrintGCTimeStamps -XX:+PrintGCDateStamps -Xloggc:$CATALINA_HOME/logs/gc.log Prints the GC log Different garbage collectors generally have the same format, but there are small differences, and G1 is more different than other garbage collectors
-Xss128k Sets the stack size per thread Experience is 3000-5000 best
-XX:MaxTenuringThreshold=6 The maximum threshold at which a new generation object enters the old generation The default 15
-XX:InitiatingHeapOccupancyPercent The percentage of heap memory usage when a concurrent GC cycle is started Garbage collectors like G1 use it to trigger concurrent GC cycles based on the utilization of the entire heap, not just the memory usage ratio of a particular generation. A value of 0 means always execute GC loop. The default value is 45
-XX:G1HeapWastePercent The percentage of allowed wasted heap space For the G1 garbage collector. The default is 10%, and MixedGC is not triggered if the concurrent tag has less than 10% of the recoverable space
-XX:ConcGCThreads=n Number of threads used by the concurrent garbage collector Default values vary depending on the platform on which the JVM is running
-XX:G1MixedGCLiveThresholdPercent=65 Old locale usage thresholds to include in the mixed garbage collection cycle The default occupancy rate is 65%
-XX:G1MixedGCCountTarget=8 Tag set cycle is completed, the upper limit of survival data for the old area of G1MixedGCLIveThresholdPercent blending recycling target number The default is 8 mixed garbage collections, and the goal is to limit the number of mixed garbage collections to this target
-XX:G1OldCSetRegionThresholdPercent=1 When describing Mixed GC, Old Region is added to the CSet By default, G1 adds only 10% of Old regions to the CSet

Common command monitoring tool

The bin directory in the JDK provides many powerful tools to help us monitor the usage of virtual machines. Mastering the use of these common tools can help us quickly and intuitively analyze problems.

Tools and parameters are mastered in the process of continuous use. It is not necessary to read them all at once. You can browse them to get an impression.

It is suggested that you can collect this article for easy viewing when you need to use it later

The following demo is based on JDK1.8 in Linux environment. The environment and version may vary greatly.

Java(TM) SE Runtime Environment (build 1.8.0_151-b12)
Copy the code

jps

JPS: JVM Process Status Tool, a Tool for viewing Java processes. The function of this tool is very simple. It is to view the process ID and name of the Java service running in the current environment. Generally, the JPS command is used to obtain the Java process information before other commands are used.

As shown below:



JPS parameters have the following options:

options instructions
-q Only the process ID is displayed
-m Prints the parameters passed to the main() method when the virtual machine starts
-l Prints the full name of the main class, and the path to the JAR package if it is being executed
-v Output the parameters for starting a VM

jstat

Jstat: JVM Statistics Monitoring, a tool used to monitor various Statistics about the health of virtual machines. The following information is displayed: Running data of vm processes, such as class loading, memory, garbage collection, and JIT compilation.

View class loading information

Jstat -class PID 1000 10 // Displays the class load information of a Java process every 1000 milliseconds for 10 timesCopy the code

View garbage collection information

jstat -gc PID 1000 10
Copy the code



The figure above shows the situation of each district and garbage collection, and the specific meanings are as follows:

Note: C stands for Capacity and U stands for Used size

  • S0C and S1C indicate the size of S0 and S1 in the EXISTING area.
  • 2. S1U and S2U indicate the Used space.
  • 3. EC and EU indicate the total capacity and used capacity of Eden area respectively
  • 4. OC and OU represent the total space size and used space size in the old age respectively
  • 5. MC, MU: represents the total space size and used size of the method area (implemented by Metaspace in JDK1.8)
  • 6. CCSC and CCSU: represents the total size and used size of compressed class space
  • 7. YGC and YGT: The number of Cenozoic GC and the total GC time
  • 8. FGC and FGCT: Full GC times and total time of Full GC
  • 9. GCT: Total consumption time of GC

If you are not familiar with the various partitions involved in the above meaning, you can click here to learn more.

Common options of the jstat parameter

parameter instructions
-class Look at the number and size of class loads/unloads, and how long they took
-gc Statistics the total size and used size of each partition in the heap, as well as the number and time of different partitions
-gccapacity Similar to -GC, but mainly counts the maximum and minimum space used by various regions of the Java heap
-gcutil Similar to -gc, but mainly measures the amount of used space in the total space
-gccause Same as -gcutil, except that it outputs the reason why the last GC occurred
-gcnew Statistic the GC status of Cenozoic generation
-gcnewcapacity Similar to -gcnew, but mainly the maximum and minimum space used for statistics
-gcold Statistics of GC in old years
-gcoldcapacity Similar to -gcold, but the maximum and minimum Spaces used for main statistics
-gcpermcapaticy Count the maximum and minimum space used by the permanent generation
-compiler Outputs information about how the JIT compiler compiled and how long it took
-printcompilation Outputs methods that have been jIT-compiled

jstack

Jstack: Stack Trace for Java, a tool used to generate a snapshot of thread status information at the current time. This is useful for analyzing the current thread state, such as whether a thread is blocked, or whether a deadlock has occurred. Such as:

jstack PID
Copy the code



You can clearly see the status of the current thread. The name of the thread is also printed, so it is recommended to use a custom name when creating your own thread, so that if there is an exception we can easily know which thread is causing the problem.

Common options of the jStack parameter

parameter instructions
-F Force the output thread stack when a normal request is not responded to
-l Displays additional information about locks in addition to the stack
-m A C/C++ stack can be displayed when a local method is called

jinfo

Jinfo: Configuration Info For Java, a tool For viewing and modifying JVM parameters in real time.

Note that if they are modified, they can only be modified using the type manageable in the argument we printed out using the command above.

Jinfo-flag name PID Displays the value of the name attribute of a Java process. Jinfo-flags PID Displays the ASSIGNED JVM parametersCopy the code

For Boolean -xx, run the following command:

jinfo -flag [+|-]name PID
Copy the code

For a non-boolean -xx parameter, run the following command:

jinfo -flag name=value PID
Copy the code

Such as:

jmap

Jmap: Memory Map for Java, a command used to generate heap dump snapshots, i.e. dump files. Such as:

Jmap-heap PID // Prints heap memory informationCopy the code

Jmap -dump:format=b,file=/usr/heap.hprof PID // Generates dump file 1Copy the code

If an OutOfMemoryError occurs, the dump file will be automatically generated, which is very important for us to analyze the cause of OOM occurrence in production environment. Dump file is automatically generated in idea.

-XX:+HeapDumpOnOutOfMemoryError -XX:HeapDumpPath=heap.hprof
Copy the code

We use theJVM series 1To demonstrate this, use an example of heap memory provided in:





An OOM exception occurs after the operation, and you can find that the dump file has been generated in the corresponding directory.

Since we have generated the dump file, we must analyze the file, but how do we analyze the file? We definitely need a tool to analyze dump files because it is garbled when opened directly

jhat

Jhat: The JVM Heap Analysis Tool is used to analyze dump files. Such as:

jhat heap.hprof
Copy the code



Then access the address:http://localhost:7000/.



As you can see, the information presented by this tool is relatively simple, and since it is in command form, it is difficult to directly analyze the problem. In general, if there is another tool to choose from, it is not recommended to use this tool for analysis. Next, let’s look at the use of visualization tools

Visual monitoring tool

JConsole tool

JConsole: Java Monitoring and Management Console is a visual Monitoring tool that comes with the JDK. Is above such as jstat, jstack command tools such as statistical information visualization, main can view general situation of the running Java applications, monitor heap, permanent area usage information, the information such as class loading condition.

To use JConsole, run the JConsole command on the CLI or go to the JDK installation directory to find the jconsole.exe execution file and double-click it.



For local connection, it is easy to select a service and double-click it. For remote connection, JMX connection parameters need to be configured when the remote Java service is started.

The following interface is displayed:



As you can see, there are six tabs at the top that can be toggled. I won’t go into detail about what each one is used for. If you try it yourself, you can see the memory usage of each segment, the thread information (thread name is displayed), and the class loading information.

VisualVM tool

6. VisualVM: the all-in-one Java TroubleshootingTool is one of the most powerful running monitoring troubleshootingtools ever released by the JDK, and as the name suggests, it is a surprisingly full-featured tool. The main functions of VisualVM are as follows:

  • Displays information about VM processes and their configuration environment (JPS and jINFO).
  • Monitor application CPU, GC, heap, method area, and thread information (jstat, JStack capabilities).
  • Dump file generation and analysis (jMAP, Jhat function).
  • Method-level program performance analysis allows you to identify the methods that are called the most and run the longest.
  • Offline program snapshot: collect program configuration, thread dump, memory dump and other information to create a snapshot, and send the snapshot to the developer for Bug feedback
  • Plug-in processing, you can have unlimited extension possibilities

To open the VisualVM tool, you can directly enter the command: jVisualVM in the command line, or directly find the JDK installation directory to find the jVisualvm. Exe execution file, double-click to open it.



After opening it, select your local or remote application on the left (the remote service also needs to support JMX service), and then you can see the interface on the right. Note that there are only the first 5 tabs by default, and the last TAB is for plug-ins. Different plug-ins can see different functions. The plug-in I choose is com-Sun-tools-VisualVM-modules-visualgc.nbm plug-in, which is a more interesting plug-in, we analyzed beforeJava heap memory partitioningThis plugin can be used to dynamically demonstrate the memory changes in various regions of the heap. If you are interested, try it out.

Plug-in use and download

Click on the toolbar of the main interface: Tools – > Plug-in – > Downloaded – > Add Plug-in, and then install it, as shown below:



After installation, you can open it again to see an extra TAB, which can monitor memory changes in real time



Click Settings on the plug-in page to see the latest plug-in download address (VPN is required to connect) :

Dump file

If an OutOfMemoryError occurs in the production environment, we can use the dump file with VisualVM. Click File – > Load in the toolbar (be careful to select the file type) and find the corresponding dump file to open



After opening it, click “Class” :



As you can see, the Integer object is bursting the memory, because the above example is a very simple demo, which is constantly adding Integer data to the list, so the tool can clearly see that the object is broken, so we can locate the problem.

This tool can also dump files directly:



This tool can also set up automatic dump file analysis in real time:



All in all, this is a very powerful tool, and there are many other functions, and the working principle of plug-in makes it provides unlimited function expansion, you can download different plug-ins from the official website to try it out

Other tools

In addition to the official tools provided by the JVM, there are other third-party tools that can help us better analyze dump files. For example, Arthas, an online real-time analysis tool provided by Alibaba, as well as MAT and Histogram are excellent tools.

conclusion

In this article, we introduce some common parameters of the JVM, and some common monitoring tools provided by the JVM, and use an OOM example to explain how to analyze the OOM dump file, of course, the main purpose of this article is to tell you what tools are available. But there is no very detailed introduction to the use of a tool, we are all programmers, I believe that as long as you know there is such a tool, when using it can also be very easy to get started, the key lies in practice, use more to accumulate experience. After all, tools are just tools, but they can help us better analyze problems. More importantly, how to modify and optimize problems after discovering problems is the purpose of using tools. In the next article, I’ll show you how to analyze GC logs, because GC logs must be viewed in order to tune the JVM.

** Please pay attention to me, and learn and progress together **