JVM 問題排查和性能優化常用的 JDK 工具

JDK 提供了一系列用於監控、診斷 Java 進程的工具,它們在 JDK 安裝目錄的 bin 目錄下,有 jps、jcmd、jstack、jinfo、jmap 等。其中jmc、jconsole、jvisualvm 是 GUI 工具,其他大部分都是命令行工具。

cd $JAVA_HOME/bin
ls

本篇只是個入門介紹,不涉及深入分析。每一個工具都有它專門的作用,掌握使用方法只是很簡單的入門階段,更重要的是根據工具得到的信息去分析系統存在的問題以及性能瓶頸,每一個工具的使用和分析都可以單獨成文。

jps

如果你用過 Linux,那肯定熟悉 ps 命令,用來查看進程列表的。jps 就好比是 ps 命令的子集,它查詢的是當前用戶下已經啟動的 Java 進程。這是進行線上問題排查的大門鑰匙,有了它才能下手後面的動作。

下面是 jps 的幫助文檔

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

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

一般的用法是 jps -l,前面一列显示 pid,後面一列显示進程名稱。

還可以用下列參數查看更具體的 Java 進程信息,用法為 jps -lv

jstack

查看 Java 進程內當前時刻的線程快照,也就是每條線程正在執行的方法棧情況,用於定位線程停頓、死鎖等長時間等待的問題。

以下是 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 -pid 或者 jstack -l pid,打印線程狀態、棧使用情況。

如果是線上查看不方便的話,可以用命令 jstack -l pid > stack.log,輸出到文件中下載到本地查看。

jstack -m pid,打印 Java 和 Native 棧信息

如果 -l 和 -m 都不起作用的時候,可以使用 java -F pid 強制 dump。

jinfo

它的主要作用是查看 JVM 配置參數,還可以動態設置部分參數值。jinfo 使用時需要 attach 到目標 JVM 上。關於 attach jvm 可以點擊查看

使用 jinfo -h查看幫助文檔

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 pid

查看 JVM 參數,其中 Non-default VM flags 是虛擬機默認設置的參數,Command line 是用戶指定的參數,比如命令行啟動 jar 包的時候加上的參數。

jinfo -flag 參數名 pid

可以查看指定參數的值,比如查看堆的最大值(-XX:MaxHeapSize 也就是 -Xmx ):

jinfo -flag MaxHeapSize 92041

-XX:MaxHeapSize=20971520

jinfo -sysprops pid

查看系統參數

jinfo pid

查看 jvm 參數和系統參數

以上信息,如果我們用過 visualVM 等監控工具,一定非常熟悉。另外,我之前做過一個 ,也實現了這個功能。

另外,還可以修改部分參數值。

jinfo -flag [+|-] pid

jinfo -flag = pid

可以修改部分 JVM 參數。

前者可以修改布爾值參數,比如開啟簡單 GC 日誌

jinfo -flag +PrintGC 92041

後者是設置非布爾值參數的,比如設置 HeapDumpPath

jinfo -flag HeapDumpPath=/users/fengzheng/jvmlog

哪些參數是允許動態修改的呢,用下面這個命令可以查看

#Linux 和 Mac 
java -XX:+PrintFlagsInitial | grep manageable

#windows
java -XX:+PrintFlagsInitial | findstr manageable

jmap

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 -heap pid

打印 JVM 堆概要信息,包括堆配置、新生代、老生代信息

jmap -histo pid

打印類的直方圖,也就是各個類實例的個數和空間佔用情況。

如果加 :live,jamp -histo:live pid 則只打印活動類的信息。這個命令會出發 GC 動作,會導致 JVM 停頓,所以在線上環境要慎用。

jmap -dump

dump 當前 JVM 堆,一般用法如下:

#dump 所有對象在堆中的分佈情況
jmap -dump:format=b,file=/Users/fengzheng/jvmlog/jamp_dump.hprof 95463

#加:live 參數 dump 存活對象在隊中的分佈情況
jmap -dump:live,format=b,file=/Users/fengzheng/jvmlog/jamp_dump.hprof 95463

之後再用堆分析工具,比如 visualVM、JProfile、MAT 等進行分析。和我們設置

-XX:+HeapDumpOnOutOfMemoryError 參數后,在發生 OOM 的時候 dump 的堆信息是一樣的。

注意,dump 的過程會比較慢,在這個過程中會發生 JVM 停頓,而且在使用 :live 參數后,會觸發 GC 操作。

jmap -clstats pid

Java 類加載器(ClassLoader)信息,包括加載器名稱、已加載類個數、佔用空間、父加載器、是否存活、類型信息。

jmap -finalizerinfo pid

查看等待被回收的對象。

jstat

jstat 主要用來通過垃圾回收相關信息來判斷 JVM 性能問題,也可以查看類加載、編譯的情況,主要的用法是通過持續的固定時間間隔的輸出來觀察。比如每 3 秒打印一次 GC 回收次數,連續打印 10 次,通過動態的變化來觀察 GC 是否過於密集。

下面是 jstat 的幫助手冊。

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 -options 可以看到 jstat 支持查看哪些信息。

$ jstat -options
-class  #類加載情況 加載個數和空間使用
-compiler #即時編譯器信息
-gc  # GC情況 包括 young gc、full gc 次數、時間等
-gccapacity #年輕代、老年代的使用情況
-gccause #GC 統計信息和回收原因
-gcmetacapacity #显示有關metaspace大小的統計信息
-gcnew #新生代 GC 統計
-gcnewcapacity #新生代內存統計
-gcold #老年代 GC 統計
-gcoldcapacity #老年代內存使用情況
-gcutil #GC 匯總信息
-printcompilation #編譯方法統計

上述這些大多數可以對應到 visualVM 的這一部分显示

示例用法,如下是打印 5301 進程下的垃圾回收情況,-h 3 表示每 3 行輸出一次標題信息,3s 5 表示每 3s 輸出一次,一共輸出 5 次

jstat -gcutil -h 3 5301 3s 5

最後輸出的內容如下:

jstat -gcutil -h 3 5301 3s 5
  S0     S1     E      O      M     CCS    YGC     YGCT    FGC    FGCT     GCT   
 99.92   0.00  11.90  35.29  94.96  94.08     34   12.675     3    1.946   14.621
 99.92   0.00  11.90  35.29  94.96  94.08     34   12.675     3    1.946   14.621
 99.92   0.00  11.90  35.29  94.96  94.08     34   12.675     3    1.946   14.621
  S0     S1     E      O      M     CCS    YGC     YGCT    FGC    FGCT     GCT   
 99.92   0.00  11.94  35.29  94.96  94.08     34   12.675     3    1.946   14.621
 99.92   0.00  11.94  35.29  94.96  94.08     34   12.675     3    1.946   14.621

jcmd

jcmd 會將命令發送給 JVM。這些命令包括用於控制 Java Flight Recording(飛行記錄)、診斷命令等。 必須運行在 JVM 本地,不能遠程使用,並且必須用 JVM 啟動用戶執行。

通過 jps 命令找到一個 JVM 進程,然後使用下面的代碼可以看到 jcmd 支持的命令

#進程 5173 
jcmd 5173 help 

5173:
The following commands are available:
JFR.stop
JFR.start
JFR.dump
JFR.check
VM.native_memory
VM.check_commercial_features
VM.unlock_commercial_features
ManagementAgent.stop
ManagementAgent.start_local
ManagementAgent.start
GC.rotate_log
Thread.print
GC.class_stats
GC.class_histogram
GC.heap_dump
GC.run_finalization
GC.run
VM.uptime
VM.flags
VM.system_properties
VM.command_line
VM.version
help

基本包含了問題排查的常用命令,並且和上面介紹的幾個工具有部分重合。

通過命令 jcmd 5173 help GC.heap_dump 可以查詢到 GC.heap_dump 命令的使用方法,其他命令都可以通過這個方法找到使用說明

jcmd 5173 help GC.heap_dump
5173:
GC.heap_dump
Generate a HPROF format dump of the Java heap.

Impact: High: Depends on Java heap size and content. Request a full GC unless the '-all' option is specified.

Permission: java.lang.management.ManagementPermission(monitor)

Syntax : GC.heap_dump [options] <filename>

Arguments:
    filename :  Name of the dump file (STRING, no default value)

Options: (options must be specified using the <key> or <key>=<value> syntax)
    -all : [optional] Dump all objects, including unreachable objects (BOOLEAN, false)

然後通過如下代碼就可以 dump 堆信息下來了,和 jmap -dump 的作用一樣

jcmd 5173 GC.heap_dump /Users/fengzheng/jvmlog/jcmd_heap_dump.hprof

拋磚引玉就到此了,之後會對 jinfo、jmap、jstack、jstat、jcmd 做詳細說明,記得關注啊。

相關閱讀:

歡迎關注,不定期更新本系列和其他文章
古時的風箏 ,進入公眾號可以加入交流群

本站聲明:網站內容來源於博客園,如有侵權,請聯繫我們,我們將及時處理【其他文章推薦】

※為什麼 USB CONNECTOR 是電子產業重要的元件?

網頁設計一頭霧水??該從何著手呢? 找到專業技術的網頁設計公司,幫您輕鬆架站!

※想要讓你的商品成為最夯、最多人討論的話題?網頁設計公司讓你強力曝光

※想知道最厲害的台北網頁設計公司推薦台中網頁設計公司推薦專業設計師”嚨底家”!!

您可能也會喜歡…