jstack的用法(1)

jstackisareallyhelpfulutilitythatcomesstandardwithmostlinuxJDKversions.Itallowsyoutogeneratejavathreaddumpsinsituationswherekill-3won'twork.kill-3(akakill-QUIT)willdumpajavaprocess'sthreadstostderr—butthis,ofcourse,worksonlywhenyoustillhaveaccesstostderr.Ifyou'rerunningajavaprocessasadaemon(likeajettyortomcatorjbossetcserver),stderrusuallyisinaccessible.

Fortunately,jstackallowsyoutogeneratethreaddumpswithoutneedingtoreadstderrfromtheoriginaljavaprocess.jstackwilldumpthethreadstojstack'sownstdout,whichyoucanpipetoafile,orthroughapager,orjustsenddirectlytoyourterminial.Thereafewtrickstousingit,however,whichdon'tseemtobedocumentedanywhere:

1.Usetherightjstackexecutable

jstackusuallywillworkonlyifitcamewiththesameexactJDKversionasthetargetJVMprocessisrunning.SincealotofserversenduphavingseveraldifferentJVMversionsinstalledonthem,it'simportanttomakesurethattheversionofjstackyou'retryingtouseistherightone—thejstackexecutableat/usr/bin/jstackwon'tnecessarilybecorrect.Andsincejstackdoesn'taccepta-versionflag,it'sprettyhardtotellwhichversion/usr/bin/jstackactuallyis.

SothemostreliablewaytorunjstackisfromthebindirectoryoftheJDKwhichyou'reusingtorunthetargetJVMprocess.Onubuntu,thisusuallywillbeasubdirectoryofoneoftheJDKsinthe/usr/lib/jvmdirectory(like/usr/lib/jvm/java-6-openjdk-amd64forthe64-bitversionofthejava6JDK).Inthatcase,youmightrunjstacklikethis(whenthetargetJVM'sprocessIDis12345):

/usr/lib/jvm/java-6-openjdk-amd64/bin/jstack12345

2.RunjstackasthesameuserasthetargetJVM

YouneedtorunjstackasthesameuseraswhichthetargetJVMisrunning.Forexample,ifyou'rerunningjettyasausernamedjetty,(andthejettyprocessIDis12345)usesudotoexecutejstackasthejettyuser:

sudo-ujettyjstack12345

(IlearnedthistrickfromMichaelMoser'sjstack-themissingmanualblogpost—apparentlyjstackusesanamedpipetocommunicatewiththetargetJVMprocess,andthatpipe'spermissionsallowonlytheuserwhocreatedthetargetJVMprocesstoreadorwritethepipe.)

3.Try,tryagain

Sometimes,evenifyoudothosefirsttwothings,jstackwillstilltellyoutogogetbent(orsomeotherinscrutableerrormessageofsimilarintent).I'vefoundthatifIjusttryrunningitagainacoupleoftimes,jstackmagicallywillworkonthesecondorthirdtry.

4.Don'tuse-F

Eventhoughjstacksometimesitselfwillsuggestthatyoutry-F(particularlyifyou'vegotaversionmismatchbetweenjstackandthetargetJVM),resistthetemptationto"force"it.Whenyouusejstackwiththe-Foption,jstackwillactuallystopthetargetprocess(iekill-STOP).Onlyusethe-Foptionifyourappisalreadygoodandhung(becauseitcertainlywillbeonceyouuse-F).

PostedbyJustinLudwigat11:21AM

Labels:daemon,debug,java,jstack,linux,threads

Nocomments:

PostaComment

摘自:http://blog.swwomm.com/2013/10/java-thread-dumps-for-daemons-with.html

相关推荐