JVM performance optimization (1) First acquaintance with JVM

1. Why do we optimize the JVM

In the local development environment, we rarely encounter the need to optimize the JVM, but in the production environment, we may have the following requirements:

  • The running application is "stuck", the log is not output, and the program does not respond
  • The CPU load of the server suddenly increases
  • In a multi-threaded application, how to allocate the number of threads?

The JDK version used this time is 1.8

Second, the operating parameters of the JVM

There are a lot of parameters that can be set in the jvm, so that the jvm can run efficiently in various environments, and most of the parameters can be kept by default.

2.1 Three parameter types

The parameter types of jvm are divided into three categories, namely:

  • Standard parameters

    1. -help
    2. -version
  • -X parameters (non-standard parameters)

    1. -Xint
    2. -Xcomp
  • -XX parameter (higher usage rate)

    1. -XX:newSize
    2. -XX:+UseSerialGC
2.2 Standard parameters

The standard parameters of jvm are generally very stable and will not change in future JVM versions. You can use java -help to retrieve all standard parameters
[root@localhost ~]# java -help

用法: java [-options] class [args...]
           (执行类)
   或  java [-options] -jar jarfile [args...]
           (执行 jar 文件)
其中选项包括:
    -d32          使用 32 位数据模型 (如果可用)
    -d64          使用 64 位数据模型 (如果可用)
    -server       选择 "server" VM
                  默认 VM 是 server.

    -cp <目录和 zip/jar 文件的类搜索路径>
    -classpath <目录和 zip/jar 文件的类搜索路径>
                  用 ; 分隔的目录, JAR 档案
                  和 ZIP 档案列表, 用于搜索类文件。
    -D<名称>=<值>
                  设置系统属性
    -verbose:[class|gc|jni]
                  启用详细输出
    -version      输出产品版本并退出
    -version:<值>
                  警告: 此功能已过时, 将在
                  未来发行版中删除。
                  需要指定的版本才能运行
    -showversion  输出产品版本并继续
    -jre-restrict-search | -no-jre-restrict-search
                  警告: 此功能已过时, 将在
                  未来发行版中删除。
                  在版本搜索中包括/排除用户专用 JRE
    -? -help      输出此帮助消息
    -X            输出非标准选项的帮助
    -ea[:<packagename>...|:<classname>]
    -enableassertions[:<packagename>...|:<classname>]
                  按指定的粒度启用断言
    -da[:<packagename>...|:<classname>]
    -disableassertions[:<packagename>...|:<classname>]
                  禁用具有指定粒度的断言
    -esa | -enablesystemassertions
                  启用系统断言
    -dsa | -disablesystemassertions
                  禁用系统断言
    -agentlib:<libname>[=<选项>]
                  加载本机代理库 <libname>, 例如 -agentlib:hprof
                  另请参阅 -agentlib:jdwp=help 和 -agentlib:hprof=help
    -agentpath:<pathname>[=<选项>]
                  按完整路径名加载本机代理库
    -javaagent:<jarpath>[=<选项>]
                  加载 Java 编程语言代理, 请参阅 java.lang.instrument
    -splash:<imagepath>
2.2.1 Actual combat

1: View jvm version
[root@localhost ~]# java -version

java version "1.8.0_201"
Java(TM) SE Runtime Environment (build 1.8.0_201-b09)
Java HotSpot(TM) Server VM (build 25.201-b09, mixed mode)
[root@localhost ~]# 

2: Set system property parameters through -D

/**
 * @program: hgyq_app
        * @ClassName TestJvm
        * @description:
        * @author: lyy
        * @create: 2020-04-21 10:49
        * @Version 1.0
        **/
public class TestJvm {

    public static void main(String[] args) {
        String str = System.getProperty("str");
        if(str == null){
            System.out.println("muxiaonong");
        }else{
            System.out.println(str);
        }
    }
}

Compile and test:

# 编译
[root@localhost ~]# javac TestJvm.java 

#测试
[root@localhost ~]# java TestJvm
muxiaonong
[root@localhost ~]# java -Dstr=520 TestJvm
520
2.2.2 -server and -client parameters

The running parameters of jvm can be set through -server or -client

  • The difference between them is that the initial heap space of the Server VM will be larger. By default, the parallel garbage collector is used, which starts slowly and runs fast.
  • Client VM will be relatively conservative, the initial heap space will be smaller, use a serial garbage collector, its goal is to make the JVM start faster, but the running speed will be slower than Serverm mode
  • When the JVM starts, it will automatically choose to use the Server or Client JVM according to the hardware and operating system.
  • 32-bit operating system
    1. If it is a Windows system, regardless of hardware configuration, the client-type JVM
    is used by default 2. If it is another operating system, the machine is configured with more than 2GB of memory and there are more than 2 CPUs. Mode, otherwise use client mode
  • 64-bit operating system
    1. Only server type, client type is not supported

Test ( this machine is a 32-bit operating system ):

# 参数操作系统位数
[root@localhost ~]# cat /proc/version
Linux version 2.6.32-358.el6.i686 (mockbuild@c6b8.bsys.dev.centos.org) (gcc version 4.4.7 20120313 (Red Hat 4.4.7-3) (GCC) ) #1 SMP Thu Feb 21 21:50:49 UTC 2013

#设置Jvm的运行参数
[root@localhost ~]# java -client -showversion TestJvm
[root@localhost ~]# java -server -showversion TestJvm

Insert picture description here

2.3 -X parameters

-X jvm parameters of non-standard parameters, different versions of jvm, the arguments might not, you can java -Xsee non-standard parameters

[root@localhost ~]# java -X
    -Xmixed           混合模式执行 (默认)
    -Xint             仅解释模式执行
    -Xbootclasspath:<用 ; 分隔的目录和 zip/jar 文件>
                      设置搜索路径以引导类和资源
    -Xbootclasspath/a:<用 ; 分隔的目录和 zip/jar 文件>
                      附加在引导类路径末尾
    -Xbootclasspath/p:<用 ; 分隔的目录和 zip/jar 文件>
                      置于引导类路径之前
    -Xdiag            显示附加诊断消息
    -Xnoclassgc       禁用类垃圾收集
    -Xincgc           启用增量垃圾收集
    -Xloggc:<file>    将 GC 状态记录在文件中 (带时间戳)
    -Xbatch           禁用后台编译
    -Xms<size>        设置初始 Java 堆大小
    -Xmx<size>        设置最大 Java 堆大小
    -Xss<size>        设置 Java 线程堆栈大小
    -Xprof            输出 cpu 配置文件数据
    -Xfuture          启用最严格的检查, 预期将来的默认值
    -Xrs              减少 Java/VM 对操作系统信号的使用 (请参阅文档)
    -Xcheck:jni       对 JNI 函数执行其他检查
    -Xshare:off       不尝试使用共享类数据
    -Xshare:auto      在可能的情况下使用共享类数据 (默认)
    -Xshare:on        要求使用共享类数据, 否则将失败。
    -XshowSettings    显示所有设置并继续
    -XshowSettings:all
                      显示所有设置并继续
    -XshowSettings:vm 显示所有与 vm 相关的设置并继续
    -XshowSettings:properties
                      显示所有属性设置并继续
    -XshowSettings:locale
                      显示所有与区域设置相关的设置并继续

-X 选项是非标准选项, 如有更改, 恕不另行通知。
2.3.1 -Xint、-Xcomp、-Xmixed
  • In interpreted mode, the -Xinttag will force the JVM to execute all the bytecode, but it will reduce the running speed, usually 10 times or more

  • -XcompThe parameter -Xintis exactly the opposite of it ( ). When the JVM is used for the first time, it will compile all the bytecode into local code, which will bring about the maximum optimization

    1. Many applications in use -Xcompthere will be some loss of performance, but than with -Xintless loss due to -Xcompnot let the full functionality of JVM start JIT compiler, JIT compiler may need to compile make a judgment if all the code is compiled, then, It makes no sense for some code that is executed only once
  • -XmixedIt is a mixed mode. The interpretation mode and the compilation mode are mixed and used, which is determined by jvm. This is the default mode of jvm and the recommended mode.

Example: Strongly set the operating mode

# 强制设置为解释模式
[root@localhost ~]# java -showversion -Xint TestJvm

# 强制设置为编译模式
# 注意:在编译模式下,第一次执行会比
[root@localhost ~]# java -showversion -Xcomp TestJvm

# 默认的混合模式
[root@localhost ~]# java -showversion -Xmixed TestJvm

Insert picture description here

2.4 -XX parameters

The -XX parameter is also a non-standard parameter, which is mainly used for tuning and debugging operations of the jvm.
-XX parameters are used in two ways, one is a boolean type, and the other is a non-boolean type:

  • boolean type

    1. Format: -XX:[+-] <name>mark enable or disable <name>attribute, + means open,-means close
    2. Such as: -XX: + DisableExplicitGC means to disable manual calling of gc operation, which means that calling System.gc () is invalid
  • Non-boolean type

    1. Format: -XX:<name>=<value>indicates <name>the value of the attribute<value>
    2. For example: -XX: NewRatio = 1 means the ratio between the new generation and the old generation
  • Whether to print GC collection details

    1. -XX:+PrintGCDetails
    2. -XX:-PrintGCDetails
  • Whether to use a serial garbage collector

    1. -XX:+UseSerialGC
    2. -XX:-UserSerialGC

After configuring the -XX: attribute value here, Insert picture description here
start our main method
Insert picture description here

2.5 -Xms and -Xmx parameters

-Xms and -Xmx are to set the initial size and maximum size of jvm's heap memory respectively
-Xmx2048m: equivalent to -XX: MaxHeapSize, set the JVM maximum heap memory to 2048M
-Xms512m: equivalent to -XX: InitialHeapSize, set the JVM initial The heap memory is 512M
. Adjust the memory size of the JVM properly, which can make full use of server resources and make the program run faster.
Example:

[root@localhost ~]# java -Xms512m -Xmx2048m TestJvm
muxiaonong
2.6 View running parameters of jvm

Sometimes we need to check the running parameters of the jvm. There may be two situations for this requirement:
first, print the running parameters when running the java command;
second, view the parameters of the running java process;

2.6.1 Print parameters when running the java command
java -XX:+PrintFlagsFinal -version
Insert picture description here

As can be seen in the above-mentioned information, a boolean parameters and numeric type, the operator is the value =or :=values representing the default value and the modified

Three, JVM memory model

The memory model of jvm has a big difference between 1.7 and 1.8. Although 1.8 is used as an example in this article, we will also understand the memory model of 1.7. So let's first understand the memory model of 1.7 learning 1.8

3.1, jdk1.7 heap memory model

Insert picture description here

  • The Young area (generation) The
    Young area is divided into three parts, the Eden area and the two Survivor areas of exactly the same size. Among the Survivor areas, only one of them is used at a time, and the other is reserved for garbage collection. For copying objects, when the Eden interval becomes full, the GC will move the surviving objects to the free Survivor interval. According to the JVM strategy, after several garbage collections, the objects that still survive in Survivor are moved to Tenured interval.

  • Tenured The
    Tenured area mainly saves objects with a long life cycle, generally some old objects. When some objects are copied and transferred by Young for a certain number of times, the objects will be transferred to the Tenured area. Generally, if the application level is used in the system Cache, objects in the cache are often transferred to this interval

  • Permanent Perm region
    Perm MAIN save class、method、filed对象, this space is generally not part of the overflow, unless a disposable loading a lot of class, but in design to the hot deployment of application servers when sometimes encounter java.lang.OutOfMempryError:PermGen Spacea bug that caused this error A big reason is that it may be redeployed every time, but after redeployment, the class class is not uninstalled, which causes a large number of class objects to be saved in perm. In this case, generally restart the application server. Solve the problem

  • Virtual area
    The difference between the maximum memory and the initial memory is the Virtual area

3.2, jdk1.8 heap memory model

Insert picture description here

It can be seen from the above figure that the memory model of jdk1.8 is composed of 2 parts, young generation + old generation
young generation: Eden + 2 * Survivor
old generation: OldGen
in the Perm area with the largest change in jdk1.8, use The replacement of Metaspace (metadata space)
needs special explanation: the memory space occupied by Metaspace is not inside the virtual machine, but in the local memory space, which is the biggest difference from the permanent generation of 1.7

Insert picture description here

3.3 Why should the permanent area in 1.7 be abandoned?

About why the permanent area in 1.7 is abandoned, we can see the description on the official website, the official website address: http://openjdk.java.net/jeps/122

This is part of the JRockit and Hotspot convergence effort. JRockit customers do not need to configure the permanent generation (since JRockit does not have a permanent generation) and are accustomed to not configuring the permanent generation.

#Removing the permanent generation is an effort to integrate Hot Spot JVm and JRockit VM, because Jrockit does not have a permanent generation, and there is no need to configure a permanent generation

In our actual use, because the permanent generation of memory is often not enough or a memory leak occurs and an exception is reported java.lang.OutOfMempryError:PermGen, the permanent area is abandoned and the meta space is used instead of using the local memory space.

3.4. View heap memory usage through jstat command

The jstat command can view the usage of various parts of the heap memory and the number of loaded classes. The format of the command is as follows:
jstat [-命令选项] [vmid] [间隔时间/毫秒] [查询次数]

3.4.1 View class loading statistics
[root@localhost ~]# jstat -class 20736
Insert picture description here
Explanation:

method description
Loaded Number of loaded classes
Bytes Space occupied
Unloaded Unloaded quantity
Bytes Space not loaded
Time time

3.4.2 View compilation statistics

[root@localhost ~]# jstat -compiler 20736
Insert picture description here

method description
Compiled Number of compilations
Failed Number of failures
Invalid Unavailable quantity
Time time
FailedType Failure type
FailedMethod Failing method

3.4.3 Statistics of garbage collection
[root@localhost ~]# jstat -gc 20736

Insert picture description here
S0C: The size of the first Survivor area (KB)
S1C: The size of the second Survivor area (KB)
S0U: The size of the first Survivor area (KB) S1U: The size of the
second Survivor area (KB)
EC: Eden area size (KB)
EU: Eden area size (KB)
OC: Old area size (KB)
OU: Old area size (KB)
MC: Method area size (KB)
MU: Method area size (KB)
CCSC: Compressed class space size (KB)
CCSU: Compressed class space use size (KB)
YGC: Young generation garbage collection times
YGCT: Young generation garbage collection time
FGC: Old generation garbage collection times
FGCT: Old generation garbage collection times Elapsed time
GCT: total time consumed by garbage collection

4. Summary

The article is finished here. Brothers in doubt can discuss or leave a message below. I also wish you all a happy year, healthy and healthy, and a good job. Come on, I am a small farmer!

Published 62 original articles · praised 478 · 200,000 views

Guess you like

Origin blog.csdn.net/qq_14996421/article/details/105651927