一文带你摸清JVM性能监控、故障排查以及案例说明

2021-02-14  本文已影响0人  程序员技术客栈

开篇

给一个系统定位问题的时候,知识、经验是关键基础,数据是依据,工具是运用知识处理数据的手段。今天这里所说的数据包括但不限于异常堆栈、JVM运行日志、垃圾回收日志、线程快照、堆快照等。如何使用分析工具能提升咱们分析数据以及定位并解决问题的效率。这篇文章主要回顾下JVM中故障排查常用的命令以及案例说明。

常用命令

JDK提供了一系列的用于监控、诊断Java进程的工具,它们在JDK安装目录bin目录下,我们该如何使用它去得到有用的信息并分析系统问题以及性能瓶颈呢?下面详细介绍。

jps:JVM进程状态工具

在linux下我们肯定使用过ps -ef | grep java命令查看过正在运行的Java进程,
而在java中也提供了类似的命令,此命令可以列出正在运行的虚拟机进程,并显示虚拟机执行主类名称以及进程的唯一ID。

jps帮助文档:

usage: jps [-help]
       jps [-q] [-mlvV] [<hostid>]

Definitions:
    <hostid>:      <hostname>[:<port>]

执行案例:

jps -l
1228 sun.tools.jps.Jps

option参数说明:

jstat:JVM统计信息监视工具

此命令可以查看JVM运行状态。可以显示本地或者远程JVM进程中的类加载、内存、垃圾收集、即时编译等运行时数据。

jstat帮助文档:

invalid argument count
Usage: jstat -help|-options
       jstat -<option> [-t] [-h<lines>] <vmid> [<interval> [<count>]]

Definitions:
  <option>      An option reported by the -options option
  <vmid>        Virtual Machine Identifier. A vmid takes the following form:
                     <lvmid>[@<hostname>[:<port>]]
                Where <lvmid> is the local vm identifier for the target
                Java virtual machine, typically a process id; <hostname> is
                the name of the host running the target Java virtual machine;
                and <port> is the port number for the rmiregistry on the
                target host. See the jvmstat documentation for a more complete
                description of the Virtual Machine Identifier.
  <lines>       Number of samples between header lines.
  <interval>    Sampling interval. The following forms are allowed:
                    <n>["ms"|"s"]
                Where <n> is an integer and the suffix specifies the units as 
                milliseconds("ms") or seconds("s"). The default units are "ms".
  <count>       Number of samples to take before terminating.
  -J<flag>      Pass <flag> directly to the runtime system.

执行案例:

//查看垃圾收集等信息
jstat -gc 1441
 S0C    S1C    S0U    S1U      EC       EU        OC         OU       MC     MU    CCSC   CCSU   YGC     YGCT    FGC    FGCT     GCT   
10752.0 10752.0  0.0    0.0   65536.0   9175.5   175104.0     0.0     4480.0 780.7  384.0   76.6       0    0.000   0      0.000    0.000

option参数说明:

jinfo:Java配置信息工具

可以用来查看正在运行的Java程序的扩展参数,包括Java system属性和JVM命令行参数;也可以动态修改正在运行的JVM参数。

jinfo帮助文档:

Usage:
    jinfo [option] <pid>
        (to connect to running process)
    jinfo [option] <executable <core>
        (to connect to a core file)
    jinfo [option] [server_id@]<remote server IP or hostname>
        (to connect to remote debug server)

where <option> is one of:
    -flag <name>         to print the value of the named VM flag
    -flag [+|-]<name>    to enable or disable the named VM flag
    -flag <name>=<value> to set the named VM flag to the given value
    -flags               to print VM flags
    -sysprops            to print Java system properties
    <no option>          to print both of the above
    -h | -help           to print this help message

执行案例:

jinfo -flags 18378
Attaching to process ID 18378, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 25.261-b12
Non-default VM flags: -XX:CICompilerCount=3 -XX:InitialHeapSize=262144000 -XX:MaxHeapSize=4164943872 -XX:MaxNewSize=1388314624 -XX:MinHeapDeltaBytes=524288 -XX:NewSize=87031808 -XX:OldSize=175112192 -XX:+UseCompressedClassPointers -XX:+UseCompressedOops -XX:+UseParallelGC 

option参数说明:

jmap:Java内存映像工具

jamp命令用于生成堆转储快照。还可以查询finalize执行队列、Java堆和方法区的详细信息,例如空间使用率、当前使用的是哪一种收集器等。

jmap帮助文档:

Usage:
    jmap [option] <pid>
        (to connect to running process)
    jmap [option] <executable <core>
        (to connect to a core file)
    jmap [option] [server_id@]<remote server IP or hostname>
        (to connect to remote debug server)

where <option> is one of:
    <none>               to print same info as Solaris pmap
    -heap                to print java heap summary
    -histo[:live]        to print histogram of java object heap; if the "live"
                         suboption is specified, only count live objects
    -clstats             to print class loader statistics
    -finalizerinfo       to print information on objects awaiting finalization
    -dump:<dump-options> to dump java heap in hprof binary format
                         dump-options:
                           live         dump only live objects; if not specified,
                                        all objects in the heap are dumped.
                           format=b     binary format
                           file=<file>  dump heap to <file>
                         Example: jmap -dump:live,format=b,file=heap.bin <pid>
    -F                   force. Use with -dump:<dump-options> <pid> or -histo
                         to force a heap dump or histogram when <pid> does not
                         respond. The "live" suboption is not supported
                         in this mode.
    -h | -help           to print this help message
    -J<flag>             to pass <flag> directly to the runtime system

执行案例:

jmap -dump:format=b,file=test.bin 1713
Dumping heap to /Users/handexing/test.bin ...
Heap dump file created

参数说明:

jhat:JVM堆转储快照分析工具

与jmap命令搭配使用,用来分析jmap生成的堆转储快照。jhat内置了一个微型http/web服务器,生成分析后的结果,可以在浏览器中查看(话说回来,实际情况中除非是真没别的工具可用了,否则大多数人是不会直接用jhat来分析快照的)。也不建议在服务器上使用jhat,会损耗服务器性能。

jhat帮助文档:

Usage:  jhat [-stack <bool>] [-refs <bool>] [-port <port>] [-baseline <file>] [-debug <int>] [-version] [-h|-help] <file>

    -J<flag>          Pass <flag> directly to the runtime system. For
              example, -J-mx512m to use a maximum heap size of 512MB
    -stack false:     Turn off tracking object allocation call stack.
    -refs false:      Turn off tracking of references to objects
    -port <port>:     Set the port for the HTTP server.  Defaults to 7000
    -exclude <file>:  Specify a file that lists data members that should
              be excluded from the reachableFrom query.
    -baseline <file>: Specify a baseline object dump.  Objects in
              both heap dumps with the same ID and same class will
              be marked as not being "new".
    -debug <int>:     Set debug level.
                0:  No debug output
                1:  Debug hprof file parsing
                2:  Debug hprof file parsing, no server
    -version          Report version number
    -h|-help          Print this help and exit
    <file>            The file to read

For a dump file that contains multiple heap dumps,
you may specify which dump in the file
by appending "#<number>" to the file name, i.e. "foo.hprof#3".

All boolean options default to "true"

执行案例:

jhat test.bin  
Reading from dump.bin...
Dump file created Sat Feb 8 21:54:58 CST 2021
Snapshot read, resolving...
Resolving 271309 objects...
Chasing references, expect 54 dots......................................................
Eliminating duplicate references......................................................
Snapshot resolved.
Started HTTP server on port 7000
Server is ready.

访问localhost:7000可以查看分析结果。

jstack:Java堆栈跟踪工具

用于生成JVM当时的线程快照。线程快照就是当前JVM内每一条线程正在执行的方法堆栈集合。生成快照主要用于定位线程长时间停顿的原因,例如死锁、死循环、请求资源导致长时间挂起等。就可以排查到没有相应的线程到底在干什么。

jstack帮助文档:

Usage:
    jstack [-l] <pid>
        (to connect to running process)
    jstack -F [-m] [-l] <pid>
        (to connect to a hung process)
    jstack [-m] [-l] <executable> <core>
        (to connect to a core file)
    jstack [-m] [-l] [server_id@]<remote server IP or hostname>
        (to connect to a remote debug server)

Options:
    -F  to force a thread dump. Use when jstack <pid> does not respond (process is hung)
    -m  to print both java and native frames (mixed mode)
    -l  long listing. Prints additional information about locks
    -h or -help to print this help message

执行案例:

jstack -l 1713
2021-02-08 20:16:16
Full thread dump Java HotSpot(TM) 64-Bit Server VM (25.261-b12 mixed mode):

"DestroyJavaVM" #53 prio=5 os_prio=31 tid=0x00007fa898808800 nid=0x1103 waiting on condition [0x0000000000000000]
   java.lang.Thread.State: RUNNABLE

   Locked ownable synchronizers:
    - None

"http-nio-8080-AsyncTimeout" #51 daemon prio=5 os_prio=31 tid=0x00007fa898a4a000 nid=0x7903 waiting on condition [0x0000700007b0b000]
   java.lang.Thread.State: TIMED_WAITING (sleeping)
    at java.lang.Thread.sleep(Native Method)
    at org.apache.coyote.AbstractProtocol$AsyncTimeout.run(AbstractProtocol.java:1133)
    at java.lang.Thread.run(Thread.java:748)

   Locked ownable synchronizers:
    - None

option参数说明:

案例说明

OOM分析

Java代码案例:

/**
 * @author handx
 * @version 1.0.0
 * @ClassName Heap.java
 * @Description TODO
 * @createTime 2021年02月08日 20:47:00
 */
public class HeapOOM {

    private static class OOMObject{}

    public static void main(String[] args) {
        ArrayList<OOMObject> oomObjects = new ArrayList<OOMObject>();

        while (true){
            oomObjects.add(new OOMObject());
        }
    }
}

VM opetion配置:

-Xms20m -Xmx20m -XX:+HeapDumpOnOutOfMemoryError  -XX:HeapDumpPath=./

或使用jmap命令也可以拉取一份堆转储文件。

程序执行完毕打印:

java.lang.OutOfMemoryError: Java heap space
Dumping heap to ./java_pid1824.hprof ...
Heap dump file created [27809333 bytes in 0.075 secs]

使用jvisualvm进行分析(JDK自带的工具)将dump文件导入进来:

image

打开选项卡,可以看到第一个就是我们自己创建的对象:

image

也可以查看堆转储上的线程信息:


image

这个地方基本上已经看出是具体哪一行代码有问题了,该修复修复了。

写在最后

简单介绍了JVM中常用的命令,想要熟练使用还要在日常开发调试中经常使用,熟能生巧。下次复习下怎样对GC日志分析,希望这篇文章能给大家带来帮助。喜欢加关注,后续持续更新!!!

上一篇下一篇

猜你喜欢

热点阅读