JVM 調優 - jhat
Java命令學習系列(五)——jhat
2016-01-21 分類:Java 閱讀(8708) 評論(3)阿里大牛珍藏架構資料,點選連結免費獲取
jhat(Java Heap Analysis Tool),是一個用來分析java的堆情況的命令。之前的文章講到過,使用jmap可以生成Java堆的Dump檔案。生成dump檔案之後就可以用jhat命令,將dump檔案轉成html的形式,然後通過http訪問可以檢視堆情況。
jhat命令解析會Java堆dump並啟動一個web伺服器,然後就可以在瀏覽器中檢視堆的dump檔案了。
例項
一、匯出dump檔案
關於dump檔案的生成可以看jmap命令的詳細介紹.
1、執行java程式
/**
* Created by hollis on 16/1/21.
*/
public class JhatTest { public static void main(String[] args) { while(true) { String string = new String("hollis"); System.out.println(string); } } }
2、檢視該程序的ID
HollisMacBook-Air:apaas hollis$ jps -l 68680 org.jetbrains.jps.cmdline.Launcher 62247 com.intellij.rt.execution.application.AppMain 69038 sun.tools.jps.Jps
使用jps命令檢視發現有三個java程序在執行,一個是我的IDEA使用的程序68680,一個是JPS命令使用的程序69038,另外一個就是上面那段程式碼執行的程序62247。
3、生成dump檔案
HollisMacBook-Air:test hollis$ jmap -dump:format=b,file=heapDump 62247 Dumping heap to /Users/hollis/workspace/test/heapDump ... Heap dump file created
以上命令可以將程序6900的堆dump檔案匯出到heapDump檔案中。 檢視當前目錄就能看到heapDump檔案。
除了使用jmap命令,還可以通過以下方式:
1、使用 jconsole 選項通過 HotSpotDiagnosticMXBean 從執行時獲得堆轉儲(生成dump檔案)、
2、虛擬機器啟動時如果指定了 -XX:+HeapDumpOnOutOfMemoryError 選項, 則在丟擲 OutOfMemoryError 時, 會自動執行堆轉儲。
3、使用 hprof 命令
二、解析Java堆轉儲檔案,並啟動一個 web server
HollisMacBook-Air:apaas hollis$ jhat heapDump Reading from heapDump... Dump file created Thu Jan 21 18:59:51 CST 2016 Snapshot read, resolving... Resolving 341297 objects... Chasing references, expect 68 dots.................................................................... Eliminating duplicate references.................................................................... Snapshot resolved. Started HTTP server on port 7000 Server is ready.
使用jhat命令,就啟動了一個http服務,埠是7000
然後在訪問http://localhost:7000/
頁面如下:
三、分析
在瀏覽器裡面看到dump檔案之後就可以進行分析了。這個頁面會列出當前程序中的所有對像情況。
該頁面提供了幾個查詢功能可供使用:
All classes including platform// Show all members of the rootset Show instance counts for all classes (including platform) Show instance counts for all classes (excluding platform) Show heap histogram Show finalizer summary Execute Object Query Language (OQL) query
一般檢視堆異常情況主要看這個兩個部分:
Show instance counts for all classes (excluding platform),平臺外的所有物件資訊。如下圖:
Show heap histogram 以樹狀圖形式展示堆情況。如下圖:
具體排查時需要結合程式碼,觀察是否大量應該被回收的物件在一直被引用或者是否有佔用記憶體特別大的物件無法被回收。
用法摘要
這一部分放在後面介紹的原因是一般不太使用。
HollisMacBook-Air:~ hollis$ jhat -help 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