How to print stack trace of a thread (with thread id) via bash command?

1k views Asked by At

I would try to monitor the action performed on a thread something like tail command. And it should print the stackTrace of the thread (whose thread id is known).

I could print the stack trace of all the threads which is currently running under the java process like the following

pid=$(ps -ef |grep 'catalina' | grep java | awk ' { print $2 } ');
eval '/home/jdk/bin/jstack -F $pid' > stack_trace.txt

But I need to print stack trace of the thread whose thread id is known.

Any help in this regard is most welcome. Thanks in advance :)

1

There are 1 answers

0
giddi On

Can you try to see if below works for you.

TARGET_THREAD_ID=xxx JAVA_PID=$(ps -ef | grep "[org].apache.catalina.startup.Bootstrap"  | awk '{print $2}'); jstack -F ${JAVA_PID} | sed -n -e "/Thread ${TARGET_THREAD_ID}/,/Thread /p" | head -n -1

Which will print something like below

Thread xxx: (state = BLOCKED)
 - java.lang.Object.wait(long) @bci=0 (Compiled frame; information may be imprecise)
 - java.lang.Object.wait() @bci=2, line=502 (Compiled frame)
 - java.lang.ref.Reference.tryHandlePending(boolean) @bci=54, line=191 (Compiled frame)
 - java.lang.ref.Reference$ReferenceHandler.run() @bci=1, line=153 (Compiled frame)