Java命令學習系列(五)——jhat
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 dump