java線程dump能夠使用jdk的命令「jstack pid」完成,死鎖檢查能夠用jconsole查看到。這兩個工具是java調試的經常使用方法。java
我遇到的問題是:在sles11sp3的服務上面測試,上面只有IBM J9 VM jre,默認沒有裝jdk,裝了jdk後發現沒有jstack命令,因爲系統沒有啓動圖形界面,jconsole也沒法使用,最後安裝了vnc server,在xterm裏面打開jconsole才定位到問題。web
因而我想作一個不依賴jdk,在J9 VM jre和oracle的 jre下均可以打印堆棧的工具。因而就有了下面的東西。oracle
這個工具只能獲取到當前JVM的堆棧,須要經過外圍的接口輸出,好比http server、web service等等。代碼主要是從jconsole的源碼裏面弄出來的。輸出的格式和jstack一致。工具
原理是使用ThreadMXBean獲取線程棧信息,而後輸出,測試
ThreadMXBean rtb = ManagementFactory.getThreadMXBean();....
裏面的_.$是一個MessageFormater工具類方法,我使用的是org.slf4j.helpers.MessageFormatter,沒有上傳。spa
測試用例輸出以下,能夠看出t1和t2死鎖了。線程
2014-09-04 15:08:57.565 Full thread dump Java HotSpot(TM) 64-Bit Server VM Sun Microsystems Inc. 20.45-b01 deadlock #0:t1 - t2 "t2" with id 10,state:BLOCKED on java.lang.Object@3ea981ca owned by t1 ,blocked:2,waited:0 com.skybility.ha.cmm.common.trace.DeadLock1.method2(DeadLock1.java:22) - locked java.lang.Object@6d9efb05 com.skybility.ha.cmm.common.trace.DeadLock1$Thread2.run(DeadLock1.java:50) "t1" with id 9,state:BLOCKED on java.lang.Object@6d9efb05 owned by t2 ,blocked:3,waited:0 com.skybility.ha.cmm.common.trace.DeadLock1.method1(DeadLock1.java:12) - locked java.lang.Object@3ea981ca com.skybility.ha.cmm.common.trace.DeadLock1$Thread1.run(DeadLock1.java:36) "Attach Listener" with id 5,state: RUNNABLE,blocked:0,waited:0 "Signal Dispatcher" with id 4,state: RUNNABLE,blocked:0,waited:0 "Finalizer" with id 3,state:WAITING on java.lang.ref.ReferenceQueue$Lock@6a8814e9 ,blocked:0,waited:1 java.lang.Object.wait(Native Method) java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:118) java.lang.ref.ReferenceQueue.remove(ReferenceQueue.java:134) java.lang.ref.Finalizer$FinalizerThread.run(Finalizer.java:171) "Reference Handler" with id 2,state:WAITING on java.lang.ref.Reference$Lock@c1503a3 ,blocked:0,waited:1 java.lang.Object.wait(Native Method) java.lang.Object.wait(Object.java:485) java.lang.ref.Reference$ReferenceHandler.run(Reference.java:116) "main" with id 1,state: RUNNABLE,blocked:0,waited:1 sun.management.ThreadImpl.dumpThreads0(Native Method) sun.management.ThreadImpl.dumpAllThreads(ThreadImpl.java:433) com.skybility.ha.cmm.common.ThreadDumper.dump(ThreadDumper.java:31) com.skybility.ha.cmm.common.trace.TestStackDump.main(TestStackDump.java:22)